Die Klasse variant

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

Einführung

VARIANT ist COMs Pendant von PHPs zval; es ist eine Struktur, die einen Wert einer Reihe unterschiedlicher möglicher Typen enthalten kann. Mit der Klasse variant, die von der Erweiterung COM zur Verfügung gestellt wird, kann die Art und Weise, wie PHP Werte an COM übergibt und von COM erhält, besser kontrolliert werden.

Klassenbeschreibung

class variant {
/* Methoden */
public __construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)
}

variant-Beispiele

Beispiel #1 variant-Beispiel

<?php
$v = new variant(42);
print "Der Typ ist " . variant_get_type($v) . "<br/>";
print "Der Wert ist " . $v . "<br/>";
?>

Hinweis:

Wenn ein Wert zurückgegeben oder eine variant-Eigenschaft abgerufen wird, wird variant nur dann in einen PHP-Wert konvertiert, wenn es eine direkte, verlustlose Zuordnung zwischen den Typen gibt. In allen anderen Fällen wird das Ergebnis als Instanz der variant-Klasse zurückgegeben. Es ist möglich PHP zu zwingen, die Variante in einen nativen PHP-Typ zu konvertieren, entweder durch explizite Verwendung eines Operators für die Typumwandlung oder implizit durch die Umwandlung in einen String mittels print. Die breite Palette von variant-Funktionen kann verwendet werden, um arithmetische Operationen auf Varianten durchzuführen, ohne eine Konvertierung zu erzwingen und damit Datenverlust zu riskieren.

Siehe auch variant_get_type().

Inhaltsverzeichnis

  • variant::__construct — Der variant-Klassenkonstruktor

User Contributed Notes

darren at dcook dot org 17-Jul-2007 05:59
If you are frustrated that print_r($obj) (where $obj is something returned from a call to a function on a COM object) does not return anything helpful, and that variant_get_type($obj) just returns a number, the function you are actually after is:
  com_print_typeinfo($obj);

It lists all functions, variables, their types in a human-readable (well, programmer-readable) format. Lovely!
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:50
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


Der variant-Klassenkonstruktor

  • « variant
  • COMPersistHelper »
  • PHP Manual
  • variant
  • Der variant-Klassenkonstruktor

variant::__construct

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

variant::__construct — Der variant-Klassenkonstruktor

Beschreibung

public variant::__construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)

Erstellt ein neues variant-Objekt.

Parameter-Liste

value
Der Anfangswert. Ist er nicht angegeben oder auf null gesetzt, wird ein VT_EMPTY-Objekt erzeugt.
type
Spezifiziert den Typ des Inhalts des variant-Objektes. Mögliche Werte für VT_XXX sind unter Vordefinierte Konstanten zu finden. PHP kann Parameter, die per Referenz übergeben wurden, automatisch erkennen; sie müssen nicht einmal als variant-Objekte übergeben werden. Die MSDN-Bibliothek kann für zusätzliche Informationen über den Typ VARIANT konsultiert werden.
codepage
Gibt die Codepage an, welche zur Konvertierung von Zeichenketten in Unicode verwendet wird. Siehe den gleichnamigen Parameter in der com-Klasse für mehr Informationen.

User Contributed Notes

There are no user contributed notes for this page.


The COMPersistHelper class

(PHP 5, PHP 7, PHP 8)

Einführung

COMPersistHelper improves the interoperability of COM and PHP with regard to the php.ini directive open_basedir, and stream Ressources.

Klassenbeschreibung

final class COMPersistHelper {
/* Methoden */
public __construct(?variant $variant = null)
public GetCurFileName(): string|false
public GetMaxStreamSize(): int
public InitNew(): bool
public LoadFromFile(string $filename, int $flags = 0): bool
public LoadFromStream(resource $stream): bool
public SaveToFile(?string $filename, bool $remember = true): bool
public SaveToStream(resource $stream): bool
}

Inhaltsverzeichnis

  • COMPersistHelper::__construct — Construct a COMPersistHelper object
  • COMPersistHelper::GetCurFileName — Get current filename
  • COMPersistHelper::GetMaxStreamSize — Get maximum stream size
  • COMPersistHelper::InitNew — Initialize object to default state
  • COMPersistHelper::LoadFromFile — Load object from file
  • COMPersistHelper::LoadFromStream — Load object from stream
  • COMPersistHelper::SaveToFile — Save object to file
  • COMPersistHelper::SaveToStream — Save object to stream

User Contributed Notes

There are no user contributed notes for this page.


Construct a COMPersistHelper object

  • « COMPersistHelper
  • COMPersistHelper::GetCurFileName »
  • PHP Manual
  • COMPersistHelper
  • Construct a COMPersistHelper object

COMPersistHelper::__construct

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::__construct — Construct a COMPersistHelper object

Beschreibung

public COMPersistHelper::__construct(?variant $variant = null)

Constructs a persistence helper object, usually associated with a variant.

Parameter-Liste

variant
A COM object which implements IDispatch. To be able to successfully call any of COMPersistHelper's methods, the object has to implement IPersistFile, IPersistStream and/or IPersistStreamInit. Passing null as variant is only useful if the object is to be loaded from a stream by calling COMPersistHelper::LoadFromStream().

User Contributed Notes

There are no user contributed notes for this page.


Get current filename

  • « COMPersistHelper::__construct
  • COMPersistHelper::GetMaxStreamSize »
  • PHP Manual
  • COMPersistHelper
  • Get current filename

COMPersistHelper::GetCurFileName

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetCurFileName — Get current filename

Beschreibung

public COMPersistHelper::GetCurFileName(): string|false

Retrieves the current name of the file associated with the object.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the current name of the file associated with the object.

Fehler/Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::GetCurFile() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Get maximum stream size

  • « COMPersistHelper::GetCurFileName
  • COMPersistHelper::InitNew »
  • PHP Manual
  • COMPersistHelper
  • Get maximum stream size

COMPersistHelper::GetMaxStreamSize

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetMaxStreamSize — Get maximum stream size

Beschreibung

public COMPersistHelper::GetMaxStreamSize(): int

Retrieves the size of the stream (in bytes) needed to save the object.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the size of the stream (in bytes) needed to save the object.

Fehler/Exceptions

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::GetSizeMax() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Initialize object to default state

  • « COMPersistHelper::GetMaxStreamSize
  • COMPersistHelper::LoadFromFile »
  • PHP Manual
  • COMPersistHelper
  • Initialize object to default state

COMPersistHelper::InitNew

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::InitNew — Initialize object to default state

Beschreibung

public COMPersistHelper::InitNew(): bool

Initializes an object to a default state.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistStreamInit, or when calling its IPersistStreamInit::Init() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from file

  • « COMPersistHelper::InitNew
  • COMPersistHelper::LoadFromStream »
  • PHP Manual
  • COMPersistHelper
  • Load object from file

COMPersistHelper::LoadFromFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromFile — Load object from file

Beschreibung

public COMPersistHelper::LoadFromFile(string $filename, int $flags = 0): bool

Opens the specified file and initializes an object from the file contents.

Parameter-Liste

filename
The name of the file from which to load the object.
flags
The access mode to be used when opening the file. Possible values are taken from the » STGM enumeration. The method can treat this value as a suggestion, adding more restrictive permissions if necessary. If flags is 0, the implementation is supposed to open the file using whatever default permissions are used when a user opens the file.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from stream

  • « COMPersistHelper::LoadFromFile
  • COMPersistHelper::SaveToFile »
  • PHP Manual
  • COMPersistHelper
  • Load object from stream

COMPersistHelper::LoadFromStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromStream — Load object from stream

Beschreibung

public COMPersistHelper::LoadFromStream(resource $stream): bool

Initializes an object from the stream where it was saved previously.

Parameter-Liste

stream
The stream Ressource from which to load the object.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistStream, or when calling the IPersistStream::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Save object to file

  • « COMPersistHelper::LoadFromStream
  • COMPersistHelper::SaveToStream »
  • PHP Manual
  • COMPersistHelper
  • Save object to file

COMPersistHelper::SaveToFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToFile — Save object to file

Beschreibung

public COMPersistHelper::SaveToFile(?string $filename, bool $remember = true): bool

Saves a copy of the object to the specified file.

Parameter-Liste

filename
The name of the file to which to save the object.
remember
Indicates whether the filename parameter is to be used as the current working file. If true, filename becomes the current file and the object is supposed to clear its dirty flag after the save. If false, this save operation is a "Save A Copy As ..." operation. In this case, the current file is unchanged and the object is not supposed to clear its dirty flag.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Save() method failed.

Beispiele

Beispiel #1 Basic COMPersistHelper::saveToFile() Usage

<?php
$word = new COM('Word.Application');
$doc = $word->Documents->Add();
$ph = new COMPersistHelper($doc);
$ph->SaveToFile('C:\\Users\\cmb\\Documents\\my.docx');
$word->Quit();
?>

User Contributed Notes

There are no user contributed notes for this page.


Save object to stream

  • « COMPersistHelper::SaveToFile
  • com_exception »
  • PHP Manual
  • COMPersistHelper
  • Save object to stream

COMPersistHelper::SaveToStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToStream — Save object to stream

Beschreibung

public COMPersistHelper::SaveToStream(resource $stream): bool

Saves an object to the specified stream.

Parameter-Liste

stream
The stream Ressource to which to save the object.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::Save() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Die Klasse com_exception

(PHP 5, PHP 7, PHP 8)

Einführung

Klassenbeschreibung

final class com_exception extends Exception {
/* Geerbte Eigenschaften */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Geerbte Methoden */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The com_safearray_proxy class

(PHP 5, PHP 7, PHP 8)

Einführung

com_safearray_proxy is an internal class used for resolving multi-dimensional array accesses on SafeArray types.

Klassenbeschreibung

final class com_safearray_proxy {
}

User Contributed Notes

There are no user contributed notes for this page.


COM Funktionen

Siehe auch

For further information on COM read the » COM specification. You might find some additional useful information in our FAQ for PHP und COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

Inhaltsverzeichnis

  • 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 — Lädt eine Typelib
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — Concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

Sorin Negulescu 05-Nov-2016 10:49
I have spent a lot of hours trying to make word.application work on a Windows Server using Apache as a service.
The application was working if Apache was started from command line (not as a service).

In the hope that this will help others not to lose hours of trying to solve this problem here is what I found out:

- In php.ini make sure you have the following key under the [COM_DOT_NET]: extension=php_com_dotnet.dll
- Apache shall run under a normal user account (not SYSTEM account). Run services.msc and fill-in the info of the user under the Apache service's Properties tab.
- Make sure you are able to start MS Word normally under that user account and dismiss all the dialogs that may appear (license, your info with initials, etc.). Start Word once again and make sure no dialogs appear.
- Launch dcomcnfg.exe->Console Root->Component Services->Computers->My Computer->DCOM Config->Microsoft Office Word 97 - 2003->Right Click(Properties)->Identity Tab and fill in the same user account information as for Apache service.
- If you cannot find the Microsoft Office Word 97 - 2003, make sure you are launching the correct DCOM Config (64 bit vs 32 bit) depending on what version of Office you have installed. To launch the 32 bit version run: mmc comexp.msc /32

Before following the steps described above, the winword.exe app appears in task manager but, if you look at the memory consumption you can notice two things:
- it increases slowly
- it stops usually at about 7-8 MB.

Keywords: COM, word.application, Apache, service, winword, timeout, no error
larrywalker at at chelseagroton dot com 02-Sep-2008 08:53
To run a php script in a background process and pass it you var use

<?php

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("c:\\xampp\\php\\php.exe

c:\\xampp\\Not_on_Web\\ftptestback.php --user=$username", 7, false);

?>

Works for me.
monica at digitaldesignservices dot com 27-Dec-2007 02:41
Working with Word 2003 COM object.

Have you been trying to work with the Word.Application COM and the Word Document would crash and the PHP script would hang?

Turns out that there is an issue within the Office COM object that doesn't let the web application (IIS, Apache) scripting engine release the object after instancing the COM.  The Service Pack 3 office update claims to remedy this.  Will test and post findings.
tomfmason at nospam-gmail dot com 08-Oct-2007 07:26
To get the cpu load percentage you can do something like this.

<?php
$wmi = new COM('winmgmts://');
$processor = $wmi->ExecQuery("SELECT * FROM Win32_Processor");
foreach($processor as $obj){
    $cpu_load_time = $obj->LoadPercentage;
}
echo $cpu_load_time;
?>

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

To list current apache instances

<?php
$wmi = new COM('winmgmts://');
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'httpd.exe'");
foreach($processes as $process){
    echo $process->CommandLine . "<br />";
    echo $process->ProcessId . "<br />";
}
?>

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

To run a php script in a background process

<?php
$dir = "C:\\path\\to\\dir";
$php_path = "C:\\path\\to\\php.exe";
$file = "somescript.php";
//send time current timestamp
$cmd_options = "-t " . time();
$wscript = new COM('WScript.Shell');
$wscript->Run("cmd /K CD $php_path $dir\\$file  &  ", 0, false);
?>

Enjoy

Tom
naveed at php dot net 10-Mar-2007 05:24
Here is a spell check implementation that displays the suggestion list for each misspelled word.

<?php
function SpellCheck($input)
{
    $word=new COM("word.application") or die("Cannot create Word object");
    $word->Visible=false;
    $word->WindowState=2;
    $word->DisplayAlerts=false;
    $doc=$word->Documents->Add();
    $doc->Content=$input;
    $doc->CheckSpelling();
    $result= $doc->SpellingErrors->Count;
    if($result!=0)
    {
        echo "Input text contains misspelled words.\n\n";
        for($i=1; $i <= $result; $i++)
        {
            echo "Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
            $list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo "Suggestions: ";
            for($j=1; $j <= $list->Count; $j++)
            {
                $correct=$list->Item($j);
                echo $correct->Name.",";
            }
            echo "\n\n";
        }
    }
    else
    {
        echo "No spelling mistakes found.";
    }
    $word->ActiveDocument->Close(false);
    $word->Quit();
    $word->Release();
    $word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>
Francois-R dot Boyer at PolyMtl dot ca 13-Feb-2007 08:32
I had the problem when trying to call Access VBA scripts from PHP; the call was working but Access would never quit.  The problem was that the Apache server is running as SYSTEM, and not a user we normally use to run Office.  And as the first time a user runs Office, it asked the SYSTEM user to enter its name and initials! ;-)

To correct this problem: Stop Apache, go to Services, Apache, Properties, "Log On" tab, and check "Allow service to interact with desktop.  Restart Apache, then open your office application, in a page loaded by the Apache server, with a small PHP code like this, :

<?php
$app = new COM("Access.Application"); // or Word.Application or Excel.Application ...
$app->Visible = true; // so that we see the window on screen
?>

Put the name you want and quit the application.  Now your Office application should terminate correctly the next time you load it with a COM object in PHP.  You can stop Apache uncheck the "Allow service to interact with desktop", and restart Apache if you like.  I don't even require a Quit or anything to be sent to Access, it quits automatically when PHP terminates.

And for those who wish to know how I'm calling Access VBA scripts, instead of using ODBC or any other way to send SQL requests, which does not seem to work to call VBA scripts, I open the database as a COM object and it works fine:

<?php
$db_com = new COM("pathname of the file.mdb");
$result = $db_com->Application->Run("function_name", 'param1', 'param2', '...');
?>
03-Oct-2006 04:11
If someone want to get a COM object out of a DCOM object can do something like that:

<?php
  $dcom_obj = new COM('dacom.object','remotehost') or die("Unable to get DCOM object!");
  $com_obj = new Variant(NULL);
  $dcom_obj->Get_Module($com_obj); //user function which returns a custom IDispatch (casted as variant*)
?>

Hopefully this will help someone, because it took me quite long to figure this out.
kiotech at hotmail dot com 18-Jul-2006 06:35
For use parameters with PHP this is a Code Example

<?php
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport("//report1.rpt", 1);

      $z= $creport->ParameterFields(1)->SetCurrentValue("Mango");
      $z= $creport->ParameterFields(2)->SetCurrentValue(5000);

  $creport->ExportOptions->DiskFileName="reportin.pdf";
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$len = filesize("reportin.pdf");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");
?>
a dot kulikov at pool4tool dot com 13-Mar-2006 09:36
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you

<?php
   /***
    * Grouping Rows optically in Excel Using a COM Object
    *
    * That was not easy, I have spent several hours of trial and error to get
    * this thing to work!!!
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @since  13.03.2006
    *
    * @see    Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
    ***/

   //starting excel
   $excel = new COM("excel.application") or die("Unable to instanciate excel");
   print "Loaded excel, version {$excel->Version}\n";

   //bring it to front
   #$excel->Visible = 1;//NOT

   //dont want alerts ... run silent
   $excel->DisplayAlerts = 0;

   //create a new workbook
   $wkb = $excel->Workbooks->Add();

   //select the default sheet
   $sheet=$wkb->Worksheets(1);

   //make it the active sheet
   $sheet->activate;

   //fill it with some bogus data
   for($row=1;$row<=7;$row++){
       for ($col=1;$col<=5;$col++){

          $sheet->activate;
          $cell=$sheet->Cells($row,$col);
          $cell->Activate;
          $cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
       }//end of colcount for loop
   }

   ///////////
   // Select Rows 2 to 5
   $r = $sheet->Range("2:5")->Rows;

   // group them baby, yeah
   $r->Cells->Group;

   // save the new file
   $strPath = 'tfile.xls';
   if (file_exists($strPath)) {unlink($strPath);}
   $wkb->SaveAs($strPath);

   //close the book
   $wkb->Close(false);
   $excel->Workbooks->Close();

   //free up the RAM
   unset($sheet);

   //closing excel
   $excel->Quit();

   //free the object
   $excel = null;
?>
Pedro Heliodoro 05-Mar-2006 02:38
Using the Windows Media Player OCX and the latest snap of PHP 5.1 i was able to eject a CD-ROM drive

<?php
//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();

?>
allan666 at gmail dot com 29-Sep-2005 03:37
If you are using a COM object that opens windows or dialogs (like Office applications), those windows or dialogs will not appear and will stay invisible even if you use codes like

$word->visible = true;

To solve this problem, go to the web service properties (Administrative Tools) and click (in the Logon TAB) "Allow the Service to Iterate with desktop".

This explain lots of problems to close applications. When you try to close, the dialos asking to save the file must appear, but only in the option to iterate with desktop is on.

Hope it helps.
bruce at yourweb dot com dot au 23-Apr-2005 05:47
Simple convert xls to csv
<?php
// starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";

//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;

//open  document
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
//XlFileFormat.xlcsv file format is 6
//saveas command (file,format ......)
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);

//closing excel
$excel->Quit();

//free the object
$excel->Release();
$excel = null;
?>
michael at example dot com 23-Feb-2005 12:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
06-Jan-2005 09:11
if you want to add a new hyperlink with excel :

<?php
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
?>

I write this note because is very difficult to find
the good method to do that .

Merci beaucoup
sorin dot andrei at mymail dot ro 25-Sep-2004 02:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]

the big problem for PHP is it can't save in session an COM object

an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line  $mMap->Refresh();
the reson is he can't save the object $mMap in session

<?php
    session_start();
      if (isset($_SESSION['map'])) {
            $mMap = $_SESSION['map'];
        }
        else
        {
        $ArcIMSConnector = new COM ("aims.ArcIMSConnector")  or die("can not create AIMS message object");
            echo "Loaded ArcIMSConnector, <br>";
            $ArcIMSConnector->ServerName = "map.sdsu.edu";
            $ArcIMSConnector->ServerPort = 5300;

            $mMap = new COM ("aims.Map")  or die("can not create aims.Map message object");
            echo "Loaded aims.Map, <br>";
            print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";

            $resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");

            $mMap->Width    = 400;            //                                'Width of the map in pixels
            $mMap->Height   = 300;            //                                'Height of the map in pixels
            $mMap->BackColor = 15130848;
            $_SESSION['map'] = $mMap;
        }

    $resultRefresh = $mMap->Refresh();                                //Refresh the map
    $urlImage      = $mMap->GetImageAsUrl();
    print "<br>urlImage=$urlImage<br>";

    print "<br><IMG SRC='$urlImage'>";

/*
    $ArcIMSConnector->Release();
    $ArcIMSConnector = null;

    $mMap->Release();
    $mMap = null;
*/

?>
ferozzahid [at] usa [dot] com 24-Aug-2004 12:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.

As an example, calling a function that retrieves the name of a person will look like:

<?php
$Name = new VARIANT;

$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");

if(!$comobj->GetName($Name)) {
    echo("Could not retrieve name");
}
else {
    echo("The name retrieved is : " . $Name->value);
}
?>

$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.

Note For PHP 5:

Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.

Feroz Zahid
Shawn Coppock 11-Aug-2004 01:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.

If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.

Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.

Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:

<?php
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
?>

This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.

Hope this helps!
angelo [at] mandato <dot> com 18-May-2004 04:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
    // ado.inc.php

    $ADO_NUM = 1;
    $ADO_ASSOC = 2;
    $ADO_BOTH = 3;

    function ado_connect( $dsn )
    {
        $link = new COM("ADODB.Connection");
        $link->Open($dsn);
        return $link;
    }

    function ado_close( $link )
    {
        $link->Close();
    }

    function ado_num_fields( $rs )
    {
        return $rs->Fields->Count;
    }

    function ado_error($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Number;
    }

    function ado_errormsg($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Description;
    }

    function ado_fetch_array( $rs, $result_type,  $row_number = -1 )
    {
        global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
        if( $row_number > -1 ) // Defined in adoint.h - adBookmarkFirst    = 1
            $rs->Move( $row_number, 1 );

        if( $rs->EOF )
            return false;

        $ToReturn = array();
        for( $x = 0; $x < ado_num_fields($rs); $x++ )
        {
            if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
                $ToReturn[ $x ] = $rs->Fields[$x]->Value;
            if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
                $ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
        }
        $rs->MoveNext();
        return $ToReturn;
    }

    function ado_num_rows( $rs )
    {
        return $rs->RecordCount;
    }

    function ado_free_result( $rs )
    {
        $rs->Close();
    }

    function ado_query( $link, $query )
    {
        return $link->Execute($query);
    }

    function ado_fetch_assoc( $rs,  $row_number = -1 )
    {
        global $ADO_ASSOC;
        return  ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
    }

    function ado_fetch_row( $rs,  $row_number = -1 )
    {
        global $ADO_NUM;
        return ado_fetch_array( $rs, $ADO_NUM, $row_number);
    }

    // Extra functions:
    function ado_field_len( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Precision;
    }

    function ado_field_name( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Name;
    }

    function ado_field_scale( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->NumericScale;
    }

    function ado_field_type( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Type;
    }

?>

The aod version was a typo.
mark dickens at mindspring dot com 29-Feb-2004 08:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP.  If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account.  By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it.  Apparently accessing printers is considered "outside the realm".  I used this technique to interface a Dymo thermal label printer to my server and it works now.
alanraycom at el hogar dot net com 03-Dec-2003 03:50
XSLT transformations using MSXML can be done with this code

<?php
function xsltransform1($xslpath,$xmlstring)
 {
  $xml= new COM("Microsoft.XMLDOM");
  $xml->async=false;
  // $xmlstring is an xml string
  $xml->load($xmlstring);
  $xsl = new COM("Microsoft.XMLDOM");
  $xsl->async=false;
  // $xslpath is path to an xsl file
  $xsl->load($xslpath);
  $response=$xml->transformNode($xsl);
  unset($xml);
  unset($xsl);
  return $response;
 }
?>

enjoy
Alan Young
chris at hitcatcher dot com 01-Dec-2003 04:19
Many COM objects don't do well when passing long (win32) filenames as function parameters.  You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:

<?php
//create FSO instance
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");

//set vars
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";

//get folder & file objects
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
23-Nov-2003 09:57
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224351. The .frm file in that distribution lists most of the available properties.

<?php
// the file you wish to access
$fn = '/docs/MFA.xls';

$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);

// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";

//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);

// set a property if you wish
if (!$props->IsReadOnly()) {
  $props->Subject = 'tlc';
}
?>
brana 17-Nov-2003 05:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)

<?php
#New MAPI session...
$session = new COM("MAPI.Session");

#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);

# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";

#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("toto@toto.com", 1);   #To...
$rcpts->AddMultiple("titi@titi.com", 2);   #Cc...
$rcpts->AddMultiple("tutu@tutu.com", 3);   #Bcc...

# Resolve senders
$rcpts->Resolve();

#Send message
$msg->Send();

#Logoff
$session->Logoff();

#Cleanup
if($msg!=null) {
    $msg->Release();
    $msg = null;
}
if($session!=null) {
    $session->Release();
    $session = null;
}
?>

ps : NT account launching the service and exchange user must match !
php at dictim dot com 06-Sep-2003 01:17
This took me days to work out how to do so I gotta share it:

How to get the word count from a MS Word Document:

<?php
#Instantiate the Word component.

$word = new COM("word.application") or die("Unable to instantiate Word");

$word->Visible = 1;

$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();

echo $numwords;

$word->Quit();
?>

Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
tomas dot pacl at atlas dot cz 16-Jun-2003 06:07
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )

In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.

Example:

<?php
$myStringVariant = new VARIANT("over-write me", VT_BSTR);

/* works */
$result = $comobj->DoSomethingTo($myStringVariant );

/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );

/* The value in the variant can be retrieved by: */
$theActualValue = $myStringVariant->value;
?>
php at racinghippo dot co dot uk 22-Mar-2003 05:47
PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================

Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:

RetVal = DoSomethingTo (myVariable)

Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:

  $myStringVariant = new VARIANT("over-write me", VT_BSTR);
  $result = $comobj->DoSomethingTo( &$myStringVariant );

The value in the variant can then be retrieved by:

  $theActualValue = $myStringVariant->value;

Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:51
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
pchason at juno dot com 11-Dec-2002 11:23
Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...

<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
    }
}
//end multicolumn data output

//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
tedknightusa at hotmail dot com 26-Sep-2002 09:29
A Notes example:

<?php
$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);

$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");

$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");

// loop through
while($doc){
  $col_vals = $doc->ColumnValues();
  echo $col_vals[0];
  $doc = $view->GetNextDocument($doc);
}
?>
dwt at myrealbox dot com 27-Aug-2002 03:31
When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:

<?php

//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);

$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");

$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");

$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

?>

The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.
madon at cma-it dot com 07-Mar-2002 12:59
I thought this excel chart example could be useful.

Note the use of Excel.application vs Excel.sheet.

<pre>
<?php
    print "Hi";
#Instantiate the spreadsheet component.
#    $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");

#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";

$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook<BR>";

$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible<BR>";

$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet<BR>";
$sheets->activate; #Activate it
print "activated sheet<BR>";

#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet<BR>";
$sheets2->activate; #Activate it
print "activated sheet<BR>";

$sheets2->name="Report Second page";

$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";

# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
    $cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
    $cell->activate; #Activate the cell
    $cell->value = $i*$i; #Change it to 15000
}

$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject

$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses <BR>";

$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved<BR>";

#$ex->Application->ActiveWorkbook->Close("False");
$exapp->Quit();
unset($exapp);
?>

</pre>

Alex Madon


Generate a globally unique identifier (GUID)

  • « COM Funktionen
  • com_event_sink »
  • PHP Manual
  • COM Funktionen
  • Generate a globally unique identifier (GUID)

com_create_guid

(PHP 5, PHP 7, PHP 8)

com_create_guid — Generate a globally unique identifier (GUID)

Beschreibung

com_create_guid(): string|false

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the GUID as a string, Bei einem Fehler wird false zurückgegeben..

Siehe auch

  • uuid_create() in the PECL uuid extension

User Contributed Notes

internmail (at the google mail).com 22-Jan-2020 02:26
function create_guid() { // Create GUID (Globally Unique Identifier)
        $guid = '';
        $namespace = rand(11111, 99999);
        $uid = uniqid('', true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = substr($hash,  0,  8) . '-' .
                substr($hash,  8,  4) . '-' .
                substr($hash, 12,  4) . '-' .
                substr($hash, 16,  4) . '-' .
                substr($hash, 20, 12);
        return $guid;
    }
rogervila dot es 10-Sep-2019 02:16
I implemented a com_create_guid implementation for systems that do not support it as a Composer package in order to keep it separated from my applications

https://github.com/rogervila/com_create_guid
Dave Pearson (dave at pds-uk dot com) 14-Apr-2016 10:07
Here's my final version of a GUIDv4 function (based on others work here) that should work on all platforms and gracefully fallback to less cryptographically secure version if others are not supported...

<?php
/**
 * Returns a GUIDv4 string
 *
 * Uses the best cryptographically secure method
 * for all supported pltforms with fallback to an older,
 * less secure version.
 *
 * @param bool $trim
 * @return string
 */
function GUIDv4 ($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        if ($trim === true)
            return trim(com_create_guid(), '{}');
        else
            return com_create_guid();
    }

    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace.
              substr($charid,  0,  8).$hyphen.
              substr($charid,  8,  4).$hyphen.
              substr($charid, 12,  4).$hyphen.
              substr($charid, 16,  4).$hyphen.
              substr($charid, 20, 12).
              $rbrace;
    return $guidv4;
}
?>
indrora 08-Nov-2015 07:09
If you're going to generate random UUIDs, at least make them conform:

* The uppermost byte of the third stanza must be 4
* the uppermost byte of the fourth stanza may be any of (8 9 a b)

see also: The wikipedia page for UUIDs: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
pavel.volyntsev(at)gmail 27-Aug-2015 12:37
Use more cryptographically strong algorithm to generate pseudo-random bytes and format it as GUID v4 string

function guidv4()
{
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
Alix Axel 16-Aug-2010 03:59
The phunction PHP framework (http://sourceforge.net/projects/phunction/) uses the following function to generate valid version 4 UUIDs:

<?php

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

?>

The output generated by the sprintf() and mt_rand() calls is identical to com_create_guid() results.


Connect events from a COM object to a PHP object

  • « com_create_guid
  • com_get_active_object »
  • PHP Manual
  • COM Funktionen
  • Connect events from a COM object to a PHP object

com_event_sink

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

com_event_sink — Connect events from a COM object to a PHP object

Beschreibung

com_event_sink(variant $variant, object $sink_object, array|string|null $sink_interface = null): bool

Instructs COM to sink events generated by variant into the PHP object sink_object.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

Parameter-Liste

variant

sink_object

sink_object should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sink_interface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with variant, but you may override this choice by setting sink_interface to the name of the dispinterface that you want to use.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | sink_interface is nullable now.

Beispiele

Beispiel #1 COM event sink example

<?php
class IEEventSinker {
var $terminated = false;

function ProgressChange($progress, $progressmax) {
echo "Download progress: $progress / $progressmax\n";
}

function DocumentComplete(&$dom, $url) {
echo "Document $url complete\n";
}

function OnQuit() {
echo "Quit!\n";
$this->terminated = true;
}
}
$ie = new COM("InternetExplorer.Application");
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
com_message_pump(4000);
}
$ie = null;
?>

Anmerkungen

Achtung

Prior to PHP 8.0.0, calling exit() from any of the event handlers is not supported, and may cause PHP to hang. This can be worked around by throwing an exception from the event handler, catching the exception in the main code, and calling exit() from there.

Siehe auch

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds

User Contributed Notes

veggie 25-Dec-2016 10:23
I got voice recognition working. I'm not sure why the way I called the sink function made it work but I'm more about results right now. This small example had me rolling on the floor laughing.

<?php
/*
 * Search this for more info on the voice stuff:
 * Automation Interfaces and Objects (SAPI 5.4)
 */

//directions:
//php friend.php
//then fire up windows voice recognition and turn it on and say stuff

$voice = new COM("SAPI.SpVoice");

print "Hit control+c to end.\n";
print "Friend: Hello friend!\n";

$voice->Speak("Hello friend!");

class listen
{

    function Recognition($StreamNumber, $StreamPosition, $RecognitionType, $ISpeechRecoResult)
    {

        $phrase = $ISpeechRecoResult->PhraseInfo;
        $text = $phrase->GetText();

        print "\nYou:$text\n";

        global $voice;
        $say = array('oh', 'nice', 'humm', 'interesting', 'you dont say', 'uh huh', 'right', 'what', 'ha ha', 'you have got to be joking', 'right back at you buddy');
        $idx = rand(0, count($say)-1);

        print "Friend: " . $say[$idx] . "\n";
        $voice->Speak($say[$idx]);

    }

}

$recog = new COM("SAPI.SpSharedRecognizer");

$context = $recog->CreateRecoContext();

//SRERecognition = 16 (default)
//SREAllEvents = 393215
//$context->EventInterests = 393215;

//try to listen to events on context
$listen = new listen(); //event handler
if (!com_event_sink($context, $listen, "RecognizerStateChange"))
{
    print "Unable to sink events\n";
    exit;
}

$grammar = $context->CreateGrammar();

$i = $grammar->DictationLoad();

$s = $grammar->DictationSetState(1); //1=on, 0=off

while(true)
{

    if(!com_message_pump(1000))
    {
        print ".";
    }

}

?>
fjortiz 14-Jul-2005 12:33
In case someone needs a skeleton sink for ADODB.Connection events:

class ADOConnectionEventSink    {

    function BeginTransComplete( $translevel, $objerror, $status, $objconn )    {
        return 0;
    }

    function CommitTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function RolbackTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function WillConnect ( $ConnectionString, $userid, $psword, $options, $status, $objconn )    {
        return 0;
    }

    function ConnectComplete ( $objerror, $status, $objconn)    {
        return 0;
    }

    function Disconnect( $status, $objConn )    {
        return 0;
    }

    function WillExecute ( $src, $cursortyp, $locktyp, $options, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function ExecuteComplete ( $recaffected, $objerror, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function InfoMessage ( $objerror, $status, $objconn)    {
        return 0;
    }
}

// later on...
$db = new COM("ADODB.Connection", NULL, $charPage);
$sink = new ADOConnectionEventSink();
com_event_sink($db, $sink, "ConnectionEvents");
//...


Returns a handle to an already running instance of a COM object

  • « com_event_sink
  • com_load_typelib »
  • PHP Manual
  • COM Funktionen
  • Returns a handle to an already running instance of a COM object

com_get_active_object

(PHP 5, PHP 7, PHP 8)

com_get_active_object — Returns a handle to an already running instance of a COM object

Beschreibung

com_get_active_object(string $prog_id, ?int $codepage = null): variant

com_get_active_object() is similar to creating a new instance of a com object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the "Running Object Table" to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

Parameter-Liste

prog_id

prog_id must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

codepage

Acts in precisely the same way that it does for the com class.

Rückgabewerte

If the requested object is running, it will be returned to your script just like any other COM object.

Fehler/Exceptions

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

Changelog

Version | Beschreibung
8.0.0 | codepage is nullable now.

Anmerkungen

Warnung

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.

User Contributed Notes

gerrit at timingteam dot nl 04-Jan-2009 09:25
Please note the next behavior (Apache 2.2.8, W2K, WXP)

If Apache runs as a service, com_get_active_object() always returns MK_E_UNAVAILABLE, even when it is definitely sure that the Running Object Table contains a reference to the required object.

If Apache runs in a console, com_get_active_object()  returns the object handle as required.

This apparently is a Windows issue.


Lädt eine Typelib

  • « com_get_active_object
  • com_message_pump »
  • PHP Manual
  • COM Funktionen
  • Lädt eine Typelib

com_load_typelib

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

com_load_typelib — Lädt eine Typelib

Beschreibung

com_load_typelib(string $typelib, bool $case_insensitive = true): bool

Lädt eine Type Library und registriert deren Konstanten in der Engine, als wären sie mittels define() definiert worden.

Es ist zu beachten, dass es effizienter ist, die php.ini-Einstellungen com.typelib-file zum Vorladen und Registrieren der Konstanten zu verwenden, allerdings ist dieser Weg nicht so flexibel.

Wenn com.autoregister-typelib eingeschaltet ist, wird PHP versuchen, automatisch die mit einem COM-Objekt assoziierten Konstanten zu registrieren, wenn das Objekt initialisiert wird. Dies hängt von den Interfaces ab, die das COM-Objekt selbst unterstützt und ist nicht immer möglich.

Parameter-Liste

typelib

typelib kann eine der folgenden Angaben sein:

  • Der Dateiname der .tlb-Datei oder des ausführbaren Moduls, das die Type Library enthält.

  • Die GUID der Type Library, gefolgt von der Versionsnummer, z. B. {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • Der Name der Bibliothek, z. B. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP wird versuchen, die Type Library in dieser Reihenfolge abzuarbeiten, da der jeweils benötigte Aufwand und die dabei entstehenden "Kosten" mit jedem Punkt stärker steigen. Die Suche nach dem Namen einer Type Library erfolgt mittels physikalischer Iteration durch die Registry, bis ein Treffer gefunden wird.

case_insensitive

Der Parameter case_insensitive verhält sich genau umgekehrt wie der Parameter $case_insensitive der define()-Funktion.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

User Contributed Notes

tomas dot burba at softneta dot lt 12-Mar-2012 11:38
I had some problems with a third-party Word-controlling code that is somewhat similar to Richard's example. (Word 2007 SP1, XP SP2.) Rewrote some parts according to that example, no luck. Error messages from Word were crazy:

"Bad parameter" -- it didn't like wdGoToBookmark but was ok with its numeric equivalent -1;

"Call to undefined method variant::SaveAs()" -- the same with Save() that was suitable in my case, so no options were remaining.

But then I ran the example via php.exe in the command line, and it worked! Eventually it turned out that Apache service must be run as some real user instead of SYSTEM.
RQuadling at GMail dot com 17-Jun-2008 03:40
Some libraries load other libraries as part of their functionality. For example Crystal Reports Object Factory uses the CreateObject() method to create an instance of a Crystal Design RunTime Application. If you want to use constants defined in the newly loaded library, you will need to manually register the library - even with com.autoregister_typelib set to true.

<?php
echo 'com.autoregister_typelib = ', ini_get('com.autoregister_typelib'), PHP_EOL;

$o_CrObjectFactory = New COM('CrystalReports11.ObjectFactory.1');

$o_CrApplication = $o_CrObjectFactory->CreateObject("CrystalDesignRunTime.Application");

echo 'Will not be defined : ', crOpenReportByDefault, PHP_EOL;

com_load_typelib('CrystalDesignRunTime.Application');

echo 'Will now be defined : ', crOpenReportByDefault, PHP_EOL;
?>

outputs ...

com.autoregister_typelib = 1
Will not be defined :
Notice: Use of undefined constant crOpenReportByDefault - assumed 'crOpenReportByDefault' in C:\refl.php on line 8
crOpenReportByDefault
Will now be defined : 0
03-May-2004 07:18
In case any of you were wondering what com_load_typelib actually DOES, I have found that it loads constants\enums that the COM obeject has defined.  The example below is using the Nero COM object (from Nero Burning rom, version 6+).  The Nero object defines a bunch of constants, but they can not be used as PHP constants unless you use the mentioned function.  So the example below will work just fine:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
com_load_typelib("Nero.Nero");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

But this one will not, since PHP will return a message saying that the constant is undefined:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

This one took me a while to figure out, hope it helps.

Also, check out http://www.php.net/manual/en/faq.com.php to find out how to get COM events working in PHP.
ojpp at webdevfm dot com 30-Jan-2004 06:33
Hello PHP community, I want to help in a problem I found in this COM built-in function: com_load_typelib(), when I executed it in order to open a COM Server process (for example: Word, Excel, etc.) I was in trouble to release the object from memory, I figured it out, this is the solution:

Change a configuration in the php.ini:

; autoregister constants of a components typlib on com_load()
com.autoregister_typelib = true

When com.autoregister_typelib directive is true, PHP parser manage the COM server type library, I hope it helps.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:55
<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


Process COM messages, sleeping for up to timeoutms milliseconds

  • « com_load_typelib
  • com_print_typeinfo »
  • PHP Manual
  • COM Funktionen
  • Process COM messages, sleeping for up to timeoutms milliseconds

com_message_pump

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

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

Beschreibung

com_message_pump(int $timeout_milliseconds = 0): bool

This function will sleep for up to timeout_milliseconds milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

Parameter-Liste

timeout_milliseconds

The timeout, in milliseconds.

If you do not specify a value for timeout_milliseconds, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return false immediately without sleeping.

Rückgabewerte

If a message or messages arrives before the timeout, they will be dispatched, and the function will return true. If the timeout occurs and no messages were processed, the return value will be false.

User Contributed Notes

There are no user contributed notes for this page.


Print out a PHP class definition for a dispatchable interface

  • « com_message_pump
  • variant_abs »
  • PHP Manual
  • COM Funktionen
  • Print out a PHP class definition for a dispatchable interface

com_print_typeinfo

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

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

Beschreibung

com_print_typeinfo(variant|string $variant, ?string $dispatch_interface = null, bool $display_sink = false): bool

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

Parameter-Liste

variant

variant should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispatch_interface

The name of an IDispatch descendant interface that you want to display.

display_sink

If set to true, the corresponding sink interface will be displayed instead.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - Lädt eine Typelib

User Contributed Notes

Richard Lynch 03-Oct-2006 04:51
In my particular version of PHP, the second and third arguments are not, in fact, optional.

Passing in '' for both, however, yielded a bucketful of information.

YMMV
csaba at alum dot mit dot edu 14-Feb-2005 12:49
com_print_typeinfo is really useful if you're trying to figure out what properties and methods you have access to.  For example, I might do:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer);
?>

The first line shows me the class of the object (what VBScript calls 'typename'), in my case IShellDispatch4.  It's frequently the case that if you plunk that in as the second argument to com_print_typeinfo, you get way more methods/properties coming back.  Thus:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer, "IShellDispatch4");
?>

Furthermore, you might get additional functions listed if you try lower number suffixes (or not).  At any rate, it would be useful for PHP to have a typename function like VBScript does.  For example, if you iterate through the Windows of $oExplorer you get both IE and Explorer windows and typename is the easy way to differentiate between them.  Here's what I'm using:

<?php
    function typeName($objCOM) {
    if (empty($objCOM)) return "no COM object";
    if (gettype($objCOM)!="object") return "not a COM object";
    ob_start();
    com_print_typeinfo($objCOM);
    $typeInfo = ob_get_contents();
    ob_end_clean();
    $pattern = "/^\\s*class (.*) \\{/";
    if (!($matchCnt = preg_match($pattern, $typeInfo, $aMatch))) return "Not found";
    return $aMatch[1];
}
?>

Csaba Gabor from Vienna


Returns the absolute value of a variant

  • « com_print_typeinfo
  • variant_add »
  • PHP Manual
  • COM Funktionen
  • Returns the absolute value of a variant

variant_abs

(PHP 5, PHP 7, PHP 8)

variant_abs — Returns the absolute value of a variant

Beschreibung

variant_abs(mixed $value): variant

Returns the absolute value of a variant.

Parameter-Liste

value

The variant.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the absolute value of value.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • abs() - Absolutwert bzw. Betrag

User Contributed Notes

There are no user contributed notes for this page.


"Adds" two variant values together and returns the result

  • « variant_abs
  • variant_and »
  • PHP Manual
  • COM Funktionen
  • "Adds" two variant values together and returns the result

variant_add

(PHP 5, PHP 7, PHP 8)

variant_add — "Adds" two variant values together and returns the result

Beschreibung

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

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the result.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_sub() - Subtracts the value of the right variant from the left variant value

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise AND operation between two variants

  • « variant_add
  • variant_cast »
  • PHP Manual
  • COM Funktionen
  • Performs a bitwise AND operation between two variants

variant_and

(PHP 5, PHP 7, PHP 8)

variant_and — Performs a bitwise AND operation between two variants

Beschreibung

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

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

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

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_or() - Performs a logical disjunction on two variants

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into a new variant object of another type

  • « variant_and
  • variant_cat »
  • PHP Manual
  • COM Funktionen
  • Convert a variant into a new variant object of another type

variant_cast

(PHP 5, PHP 7, PHP 8)

variant_cast — Convert a variant into a new variant object of another type

Beschreibung

variant_cast(variant $variant, int $type): variant

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

Parameter-Liste

variant

The variant.

type

type should be one of the VT_XXX constants.

Rückgabewerte

Returns a variant of given type.

Siehe auch

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Concatenates two variant values together and returns the result

  • « variant_cast
  • variant_cmp »
  • PHP Manual
  • COM Funktionen
  • Concatenates two variant values together and returns the result

variant_cat

(PHP 5, PHP 7, PHP 8)

variant_cat — Concatenates two variant values together and returns the result

Beschreibung

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

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the result of the concatenation.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • Zeichenketten for the string concatenation operator

User Contributed Notes

There are no user contributed notes for this page.


Compares two variants

  • « variant_cat
  • variant_date_from_timestamp »
  • PHP Manual
  • COM Funktionen
  • Compares two variants

variant_cmp

(PHP 5, PHP 7, PHP 8)

variant_cmp — Compares two variants

Beschreibung

variant_cmp(
mixed $left,
mixed $right,
int $locale_id = LOCALE_SYSTEM_DEFAULT,
int $flags = 0
): int

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

Parameter-Liste

left

The left operand.

right

The right operand.

locale_id

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are null

User Contributed Notes

There are no user contributed notes for this page.


Returns a variant date representation of a Unix timestamp

  • « variant_cmp
  • variant_date_to_timestamp »
  • PHP Manual
  • COM Funktionen
  • Returns a variant date representation of a Unix timestamp

variant_date_from_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

Beschreibung

variant_date_from_timestamp(int $timestamp): variant

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

Parameter-Liste

timestamp

A unix timestamp.

Rückgabewerte

Returns a VT_DATE variant.

Siehe auch

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - Liefert den Unix-Zeitstempel für ein Datum
  • time() - Liefert den aktuellen Unix-Zeitstempel

User Contributed Notes

There are no user contributed notes for this page.


Converts a variant date/time value to Unix timestamp

  • « variant_date_from_timestamp
  • variant_div »
  • PHP Manual
  • COM Funktionen
  • Converts a variant date/time value to Unix timestamp

variant_date_to_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

Beschreibung

variant_date_to_timestamp(variant $variant): ?int

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

Parameter-Liste

variant

The variant.

Rückgabewerte

Returns a unix timestamp, or null on failure.

Siehe auch

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - Formatiert einen Unix-Zeitstempel
  • strftime() - Formatiert eine Zeit-/Datumsangabe gemäß dem Gebietsschema

User Contributed Notes

radek at tetik dot cz 25-Dec-2015 03:21
variant_date_to_timestamp() assumes the COM date in the current Windows time zone and converts it to the current PHP time zone


Returns the result from dividing two variants

  • « variant_date_to_timestamp
  • variant_eqv »
  • PHP Manual
  • COM Funktionen
  • Returns the result from dividing two variants

variant_div

(PHP 5, PHP 7, PHP 8)

variant_div — Returns the result from dividing two variants

Beschreibung

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

Divides left by right and returns the result.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise equivalence on two variants

  • « variant_div
  • variant_fix »
  • PHP Manual
  • COM Funktionen
  • Performs a bitwise equivalence on two variants

variant_eqv

(PHP 5, PHP 7, PHP 8)

variant_eqv — Performs a bitwise equivalence on two variants

Beschreibung

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

Performs a bitwise equivalence on two variants.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

If each bit in left is equal to the corresponding bit in right then true is returned, otherwise false is returned.

Fehler/Exceptions

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • « variant_eqv
  • variant_get_type »
  • PHP Manual
  • COM Funktionen
  • Returns the integer portion of a variant

variant_fix

(PHP 5, PHP 7, PHP 8)

variant_fix — Returns the integer portion of a variant

Beschreibung

variant_fix(mixed $value): variant

Gets the integer portion of a variant.

Parameter-Liste

value

The variant.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

Fehler/Exceptions

Throws a com_exception on failure.

Anmerkungen

Warnung

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

Siehe auch

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Rundet Brüche ab
  • ceil() - Rundet Brüche auf
  • round() - Rundet einen Gleitkommawert

User Contributed Notes

There are no user contributed notes for this page.


Returns the type of a variant object

  • « variant_fix
  • variant_idiv »
  • PHP Manual
  • COM Funktionen
  • Returns the type of a variant object

variant_get_type

(PHP 5, PHP 7, PHP 8)

variant_get_type — Returns the type of a variant object

Beschreibung

variant_get_type(variant $variant): int

Returns the type of a variant object.

Parameter-Liste

variant

The variant object.

Rückgabewerte

This function returns an integer value that indicates the type of variant, which can be an instance of com, dotnet or variant classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

Siehe auch

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Converts variants to integers and then returns the result from dividing them

  • « variant_get_type
  • variant_imp »
  • PHP Manual
  • COM Funktionen
  • Converts variants to integers and then returns the result from dividing them

variant_idiv

(PHP 5, PHP 7, PHP 8)

variant_idiv — Converts variants to integers and then returns the result from dividing them

Beschreibung

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

Converts left and right to integer values, and then performs integer division.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_div() - Returns the result from dividing two variants

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise implication on two variants

  • « variant_idiv
  • variant_int »
  • PHP Manual
  • COM Funktionen
  • Performs a bitwise implication on two variants

variant_imp

(PHP 5, PHP 7, PHP 8)

variant_imp — Performs a bitwise implication on two variants

Beschreibung

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

Performs a bitwise implication operation.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Variant Implication Table
If left is | If right is | then the result is
true | true | true
true | false | false
true | null | true
false | true | true
false | false | true
false | null | true
null | true | true
null | false | null
null | null | null

Fehler/Exceptions

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • « variant_imp
  • variant_mod »
  • PHP Manual
  • COM Funktionen
  • Returns the integer portion of a variant

variant_int

(PHP 5, PHP 7, PHP 8)

variant_int — Returns the integer portion of a variant

Beschreibung

variant_int(mixed $value): variant

Gets the integer portion of a variant.

Parameter-Liste

value

The variant.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Rundet Brüche ab
  • ceil() - Rundet Brüche auf
  • round() - Rundet einen Gleitkommawert

User Contributed Notes

There are no user contributed notes for this page.


Divides two variants and returns only the remainder

  • « variant_int
  • variant_mul »
  • PHP Manual
  • COM Funktionen
  • Divides two variants and returns only the remainder

variant_mod

(PHP 5, PHP 7, PHP 8)

variant_mod — Divides two variants and returns only the remainder

Beschreibung

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

Divides left by right and returns the remainder.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the remainder of the division.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Multiplies the values of the two variants

  • « variant_mod
  • variant_neg »
  • PHP Manual
  • COM Funktionen
  • Multiplies the values of the two variants

variant_mul

(PHP 5, PHP 7, PHP 8)

variant_mul — Multiplies the values of the two variants

Beschreibung

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

Multiplies left by right.

Parameter-Liste

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for false and 0 for true.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs logical negation on a variant

  • « variant_mul
  • variant_not »
  • PHP Manual
  • COM Funktionen
  • Performs logical negation on a variant

variant_neg

(PHP 5, PHP 7, PHP 8)

variant_neg — Performs logical negation on a variant

Beschreibung

variant_neg(mixed $value): variant

Performs logical negation of value.

Parameter-Liste

value

The variant.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the result of the logical negation.

Fehler/Exceptions

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs bitwise not negation on a variant

  • « variant_neg
  • variant_or »
  • PHP Manual
  • COM Funktionen
  • Performs bitwise not negation on a variant

variant_not

(PHP 5, PHP 7, PHP 8)

variant_not — Performs bitwise not negation on a variant

Beschreibung

variant_not(mixed $value): variant

Performs bitwise not negation on value and returns the result.

Parameter-Liste

value

The variant.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the bitwise not negation. If value is null, the result will also be null.

Fehler/Exceptions

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical disjunction on two variants

  • « variant_not
  • variant_pow »
  • PHP Manual
  • COM Funktionen
  • Performs a logical disjunction on two variants

variant_or

(PHP 5, PHP 7, PHP 8)

variant_or — Performs a logical disjunction on two variants

Beschreibung

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

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

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

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of performing the power function with two variants

  • « variant_or
  • variant_round »
  • PHP Manual
  • COM Funktionen
  • Returns the result of performing the power function with two variants

variant_pow

(PHP 5, PHP 7, PHP 8)

variant_pow — Returns the result of performing the power function with two variants

Beschreibung

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

Returns the result of left to the power of right.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the result of left to the power of right.

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • pow() - Potenzfunktion

User Contributed Notes

There are no user contributed notes for this page.


Rounds a variant to the specified number of decimal places

  • « variant_pow
  • variant_set_type »
  • PHP Manual
  • COM Funktionen
  • Rounds a variant to the specified number of decimal places

variant_round

(PHP 5, PHP 7, PHP 8)

variant_round — Rounds a variant to the specified number of decimal places

Beschreibung

variant_round(mixed $value, int $decimals): ?variant

Returns the value of value rounded to decimals decimal places.

Parameter-Liste

value

The variant.

decimals

Number of decimal places.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Returns the rounded value, or null on failure.

Siehe auch

  • round() - Rundet einen Gleitkommawert

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into another type "in-place"

  • « variant_round
  • variant_set »
  • PHP Manual
  • COM Funktionen
  • Convert a variant into another type "in-place"

variant_set_type

(PHP 5, PHP 7, PHP 8)

variant_set_type — Convert a variant into another type "in-place"

Beschreibung

variant_set_type(variant $variant, int $type): void

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

Parameter-Liste

variant

The variant.

type

Rückgabewerte

Es wird kein Wert zurückgegeben.

Siehe auch

  • variant_cast() - Convert a variant into a new variant object of another type
  • variant_get_type() - Returns the type of a variant object

User Contributed Notes

martin at itmission dot com 22-May-2009 10:55
In my application I was using ADODB to retrieve data from Microsoft Access.  During queries, fields defined as "Date/Time" in Access were being returned to PHP as instances of the Variant class.

For some reason, the variant_date_to_timestamp function returned incorrect timestamps.  As a workaround, I used variant_set_type($variant, VT_BSTR) to get a string representation of the date.  This can be used for most variant types PHP doesn't handle.


Assigns a new value for a variant object

  • « variant_set_type
  • variant_sub »
  • PHP Manual
  • COM Funktionen
  • Assigns a new value for a variant object

variant_set

(PHP 5, PHP 7, PHP 8)

variant_set — Assigns a new value for a variant object

Beschreibung

variant_set(variant $variant, mixed $value): void

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

Parameter-Liste

variant

The variant.

value

Rückgabewerte

Es wird kein Wert zurückgegeben.

User Contributed Notes

There are no user contributed notes for this page.


Subtracts the value of the right variant from the left variant value

  • « variant_set
  • variant_xor »
  • PHP Manual
  • COM Funktionen
  • Subtracts the value of the right variant from the left variant value

variant_sub

(PHP 5, PHP 7, PHP 8)

variant_sub — Subtracts the value of the right variant from the left variant value

Beschreibung

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

Subtracts right from left.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • variant_add() - "Adds" two variant values together and returns the result

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical exclusion on two variants

  • « variant_sub
  • win32service »
  • PHP Manual
  • COM Funktionen
  • Performs a logical exclusion on two variants

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Performs a logical exclusion on two variants

Beschreibung

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

Performs a logical exclusion.

Parameter-Liste

left

The left operand.

right

The right operand.

Hinweis:

Wie bei allen arithmetischen Variantfunktionen, können die Parameter dieser Funktion entweder native PHP-Typen (Integer, String, Fließkomma, Boolean oder null) oder Instanzen einer COM-, VARIANT- oder DOTNET-Klasse sein. Native PHP-Typen werden nach den gleichen Regeln in Varianten umgewandelt wie auch im Konstruktor der variant-Klasse. Für COM- und DOTNET-Objekte wird der Wert ihrer Standardeigenschaft genommen und als Variantenwert genutzt.

Die arithmetischen Variantenfunktionen sind Wrapper für die ähnlich benannten Funktionen der COM-Bibliothek, weiterführende Informationen hierzu finden sie in der MSDN-Bibliothek. Die PHP-Funktionen sind leicht abweichend benannt, so korrespondiert variant_add() in PHP zu VarAdd() in der MSDN-Dokumentation.

Rückgabewerte

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

Fehler/Exceptions

Throws a com_exception on failure.

Siehe auch

  • 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

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
    • Security consideration
  • Vordefinierte Konstanten
  • Win32ServiceException — The Win32ServiceException class
  • Beispiele
  • win32service Funktionen
    • 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.


Einführung

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.


Installation/Konfiguration

Inhaltsverzeichnis

  • Anforderungen
  • Installation
  • Laufzeit-Konfiguration
  • Ressource-Typen
  • Security consideration

User Contributed Notes

There are no user contributed notes for this page.


Anforderungen

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.


Installation

Information zur Installation dieser PECL-Erweiterung finden sie im Kapitel Installation von PECL-Erweiterungen. Zusätzliche Informationen wie neue Releases, Downloads, Quelldateien, Maintainerinformation und ein CHANGELOG finden Sie hier: » 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.


Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

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

Hinweis:

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

Einführung

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.

Klassenbeschreibung

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


Beispiele

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

Beispiel #2 Unregistering a service

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

Beispiel #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 Funktionen

Inhaltsverzeichnis

  • 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 Funktionen
  • win32_create_service »
  • PHP Manual
  • win32service Funktionen
  • Resumes a paused service

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Resumes a paused service

Beschreibung

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.

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

A Win32ServiceException is thrown on error.

Changelog

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

Version | Beschreibung
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.

Beispiele

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

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

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

Siehe auch

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

Beschreibung

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.

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

A Win32ServiceException is thrown on error.

Changelog

Version | Beschreibung
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.

Beispiele

Beispiel #1 A win32_delete_service() example

Deletes the dummyphp service.

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

Siehe auch

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

Beschreibung

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.

Achtung

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

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

  • 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 Funktionen
  • Pauses a service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pauses a service

Beschreibung

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.

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

A Win32ServiceException is thrown on error.

Changelog

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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

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

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Returns an array consisting of the following information on success

Prior version 1.0.0 und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

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.

Fehler/Exceptions

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

Changelog

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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

See » Microsoft ControlService function for more details

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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

Achtung

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

Parameter-Liste

exitCode

The return code used on exit.

Rückgabewerte

Return the current or old exit code.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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.

Achtung

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

Parameter-Liste

gracefulMode

true for exit graceful. false for exit with error.

Rückgabewerte

Return the current or old exit mode.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

  • 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 Funktionen
  • Update the service status

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Update the service status

Beschreibung

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.

Achtung

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

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

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

Beschreibung

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.

Achtung

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

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

Version | Beschreibung
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.

Beispiele

Beispiel #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
}
?>

Siehe auch

  • 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 Funktionen
  • Starts a service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Starts a service

Beschreibung

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.

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

A Win32ServiceException is thrown on error.

Changelog

Version | Beschreibung
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.

Siehe auch

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

User Contributed Notes

There are no user contributed notes for this page.


Stops a service

  • « win32_start_service
  • XML-Manipulation »
  • PHP Manual
  • win32service Funktionen
  • Stops a service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Stops a service

Beschreibung

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.

Parameter-Liste

servicename

The short name of the service.

machine

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Prior to version 1.0.0, wurde im Erfolgsfall WIN32_NO_ERROR zurückgegeben und false, wenn es ein Problem mit den Parametern gab oder einen Win32-Fehlercode im Fehlerfall.

Fehler/Exceptions

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

A Win32ServiceException is thrown on error.

Changelog

Version | Beschreibung
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.

Siehe auch

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

User Contributed Notes

There are no user contributed notes for this page.


XML-Manipulation

  • DOM — Document Object Model
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Beispiele
    • DOMAttr — The DOMAttr class
    • 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 — Die Klasse DOMElement
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — Die Klasse DOMEntityReference
    • DOMException — Die Klasse DOMException
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNameSpaceNode — The DOMNameSpaceNode class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — Die Klasse DOMNotation
    • DOMParentNode — The DOMParentNode interface
    • DOMProcessingInstruction — Die Klasse DOMProcessingInstruction
    • DOMText — The DOMText class
    • DOMXPath — Die Klasse DOMXPath
    • DOM Funktionen
  • libxml
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • LibXMLError — The LibXMLError class
    • libxml Funktionen
  • SimpleXML
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Beispiele
    • SimpleXMLElement — Die Klasse SimpleXMLElement
    • SimpleXMLIterator — Die Klasse SimpleXMLIterator
    • SimpleXML-Funktionen
  • WDDX
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Beispiele
    • WDDX Funktionen
  • XMLDiff — XML diff and merge
    • Einführung
    • Installation/Konfiguration
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • XML Parser
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Event Handlers
    • Case Folding
    • Error Codes
    • Character Encoding
    • Beispiele
    • XML Parser Funktionen
    • XMLParser — The XMLParser class
  • XMLReader
    • Einführung
    • Installation/Konfiguration
    • XMLReader — Die Klasse XMLReader
  • XMLWriter
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Beispiele
    • XMLWriter — The XMLWriter class
  • XSL
    • Einführung
    • Installation/Konfiguration
    • Vordefinierte Konstanten
    • Beispiele
    • XSLTProcessor — Die Klasse XSLTProcessor

User Contributed Notes

There are no user contributed notes for this page.


Document Object Model

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Beispiele
  • DOMAttr — The DOMAttr class
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::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 — Die Klasse DOMElement
    • DOMElement::after — Adds nodes after the element
    • DOMElement::append — Appends nodes after the last child node
    • DOMElement::before — Adds nodes before the element
    • DOMElement::__construct — 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 — Die Klasse DOMEntityReference
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — Die Klasse DOMException
  • 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
  • DOMNameSpaceNode — The DOMNameSpaceNode class
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adds new child at the end of the children
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::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 — Die Klasse DOMNotation
  • 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 — Die Klasse DOMProcessingInstruction
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Breaks this node into two nodes at the specified offset
  • DOMXPath — Die Klasse DOMXPath
    • 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 Funktionen
    • dom_import_simplexml — Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt

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


Einführung

Die DOM Erweiterung ermöglicht es, mit PHP durch die DOM-API auf XML-Dokumente zuzugreifen.

Hinweis:

Die Erweiterung DOM verwendet die UTF-8 Kodierung. Es kann mb_convert_encoding(), UConverter::transcode() oder iconv() verwendet werden, um mit anderen Zeichenkodierungen zu arbeiten.

User Contributed Notes

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

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

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


Installation

Diese Erweiterung ist standardmäßig aktiviert. Sie kann bei der Kompilierung mit der folgenden Option ausgeschaltet werden: --disable-dom

User Contributed Notes

There are no user contributed notes for this page.


Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (int) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (int) | 2 | Node is a DOMAttr
XML_TEXT_NODE (int) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (int) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (int) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (int) | 6 | Node is a DOMEntity
XML_PI_NODE (int) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (int) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (int) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (int) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (int) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (int) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (int) | 13 |
XML_DTD_NODE (int) | 14 |
XML_ELEMENT_DECL_NODE (int) | 15 |
XML_ATTRIBUTE_DECL_NODE (int) | 16 |
XML_ENTITY_DECL_NODE (int) | 17 |
XML_NAMESPACE_DECL_NODE (int) | 18 |
XML_ATTRIBUTE_CDATA (int) | 1 |
XML_ATTRIBUTE_ID (int) | 2 |
XML_ATTRIBUTE_IDREF (int) | 3 |
XML_ATTRIBUTE_IDREFS (int) | 4 |
XML_ATTRIBUTE_ENTITY (int) | 5 |
XML_ATTRIBUTE_NMTOKEN (int) | 7 |
XML_ATTRIBUTE_NMTOKENS (int) | 8 |
XML_ATTRIBUTE_ENUMERATION (int) | 9 |
XML_ATTRIBUTE_NOTATION (int) | 10 |
DOMException constants
Constant | Value | Description
DOM_PHP_ERR (int) | 0 | Error code not part of the DOM specification. Meant for PHP errors.
DOM_INDEX_SIZE_ERR (int) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (int) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (int) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (int) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (int) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (int) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (int) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (int) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (int) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (int) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (int) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (int) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (int) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (int) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (int) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (int) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.

User Contributed Notes

There are no user contributed notes for this page.


Beispiele

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

Beispiel #1 book.xml

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

User Contributed Notes

There are no user contributed notes for this page.


The DOMAttr class

(PHP 5, PHP 7, PHP 8)

Einführung

DOMAttr represents an attribute in the DOMElement object.

Klassenbeschreibung

class DOMAttr extends DOMNode {
/* Eigenschaften */
public readonly string $name;
public readonly bool $specified = true;
public string $value;
public readonly ?DOMElement $ownerElement;
public readonly mixed $schemaTypeInfo = null;
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $name, string $value = "")
public isId(): bool
/* Geerbte Methoden */
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
}

Eigenschaften

name

The name of the attribute.

ownerElement

The element which contains the attribute or null.

schemaTypeInfo

Not implemented yet, always is null.

specified

Not implemented yet, always is true.

value

The value of the attribute.

Hinweis:

Note, XML entities are expanded upon setting a value. Thus the & character has a special meaning. Setting value to itself will fail when value contains an &. To avoid entity expansion, use DOMElement::setAttribute() instead.

Siehe auch

  • » W3C specification of Attr

Inhaltsverzeichnis

  • 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

Beschreibung

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.

Parameter-Liste

name

The tag name of the attribute.

value

The value of the attribute.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

Beispiel #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)

Einführung

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

Klassenbeschreibung

class DOMCdataSection extends DOMText {
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $data)
/* Geerbte Methoden */
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
}

Inhaltsverzeichnis

  • 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

Beschreibung

public DOMCdataSection::__construct(string $data)

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

Parameter-Liste

data

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

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

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

Einführung

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

Klassenbeschreibung

class DOMCharacterData extends DOMNode implements DOMChildNode {
/* Eigenschaften */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* Geerbte Eigenschaften */
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;
/* Methoden */
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
/* Geerbte Methoden */
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
}

Eigenschaften

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

Version | Beschreibung
8.0.0 | The nextElementSibling and previousElementSibling properties have been added.
8.0.0 | DOMCharacterData implements DOMChildNode now.

Siehe auch

  • » W3C specification of CharacterData

Inhaltsverzeichnis

  • 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

Beschreibung

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

Adds the passed nodes after the element.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

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

Parameter-Liste

data

The string to append.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.3.0 | This function now has a tentative true return type.

Siehe auch

  • 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

Beschreibung

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

Adds the passed nodes before the node.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Deletes count characters starting from position offset.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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.

Siehe auch

  • 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

Beschreibung

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

Inserts string data at position offset.

Parameter-Liste

offset

The character offset at which to insert.

data

The string to insert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

DOM_INDEX_SIZE_ERR

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

Siehe auch

  • 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

Beschreibung

public DOMCharacterData::remove(): void

Removes the character data.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Replace count characters starting from position offset with data.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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.

Siehe auch

  • 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

Beschreibung

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

Replaces the character data with new nodes.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Returns the specified substring.

Parameter-Liste

offset

Start offset of substring to extract.

count

The number of characters to extract.

Rückgabewerte

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.

Fehler/Exceptions

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.

Siehe auch

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

Interface-Übersicht

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

Inhaltsverzeichnis

  • 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

Beschreibung

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

Adds the passed nodes after the node.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Siehe auch

  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::remove() - Removes the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::appendChild() - Adds new child at the end of the children

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

Beschreibung

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

Adds the passed nodes before the node.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Siehe auch

  • 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

Beschreibung

public DOMChildNode::remove(): void

Removes the node.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Siehe auch

  • 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

Beschreibung

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

Replaces the node with new nodes.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Siehe auch

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

Einführung

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

Klassenbeschreibung

class DOMComment extends DOMCharacterData {
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $data = "")
/* Geerbte Methoden */
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
}

Siehe auch

  • » W3C specification of Comment

Inhaltsverzeichnis

  • 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

Beschreibung

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.

Parameter-Liste

data

The value of the comment.

Beispiele

Beispiel #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> */

?>

Siehe auch

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

Einführung

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

Klassenbeschreibung

class DOMDocument extends DOMNode implements DOMParentNode {
/* Eigenschaften */
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;
/* Geerbte Eigenschaften */
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;
/* Methoden */
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
/* Geerbte Methoden */
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
}

Eigenschaften

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.

Achtung

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

validateOnParse

Loads and validates against the DTD. Default to false.

Achtung

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. A standalone document is one where there are no external markup declarations. An example of such a markup declaration is when the DTD declares an attribute with a default value.

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

Version | Beschreibung
8.0.0 | DOMDocument implements DOMParentNode now.
8.0.0 | The unimplemented method DOMDocument::renameNode() has been removed.

Anmerkungen

Hinweis:

Die Erweiterung DOM verwendet die UTF-8 Kodierung. Es kann mb_convert_encoding(), UConverter::transcode() oder iconv() verwendet werden, um mit anderen Zeichenkodierungen zu arbeiten.

Hinweis:

Wird json_encode() auf ein DOMDocument-Objekt angewendet, entspricht das dem Kodieren eines leeren Objekts.

Siehe auch

  • » W3C specification for Document

Inhaltsverzeichnis

  • 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

Beschreibung

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

Transfer a node from another document into the current document.

Parameter-Liste

node

The node to transfer.

Rückgabewerte

The node that was transfered, or false on error.

Fehler/Exceptions

DOM_NOT_SUPPORTED_ERR

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

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

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

Siehe auch

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<hello/>
beautiful
<world/>

Siehe auch

  • 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

Beschreibung

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

Creates a new DOMDocument object.

Parameter-Liste

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.

Beispiele

Beispiel #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"?> */

?>

Siehe auch

  • 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

Beschreibung

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

This function creates a new instance of class DOMAttr. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

localName

The name of the attribute.

Rückgabewerte

The new DOMAttr or false if an error occurred.

Fehler/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

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

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

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

?>

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

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

<?php

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

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

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

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

?>

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


Create new attribute node with an associated namespace

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

DOMDocument::createAttributeNS

(PHP 5, PHP 7, PHP 8)

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

Beschreibung

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

This function creates a new instance of class DOMAttr. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

namespace

The URI of the namespace.

qualifiedName

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

Rückgabewerte

The new DOMAttr or false if an error occurred.

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

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

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

An example:

<?php

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

    /*

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

    */

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

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

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

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

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

    */

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

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

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

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

    */

    /*

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

    */

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

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

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

    /*
      Result: The document remains unchanged. Output:

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

    */

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

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

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

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

    */

?>


Create new cdata node

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

DOMDocument::createCDATASection

(PHP 5, PHP 7, PHP 8)

DOMDocument::createCDATASection — Create new cdata node

Beschreibung

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

This function creates a new instance of class DOMCDATASection. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

data

The content of the cdata.

Rückgabewerte

The new DOMCDATASection or false if an error occurred.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

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

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

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

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

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

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

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


Create new comment node

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

DOMDocument::createComment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createComment — Create new comment node

Beschreibung

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

This function creates a new instance of class DOMComment. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

data

The content of the comment.

Rückgabewerte

The new DOMComment.

Changelog

Version | Beschreibung
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

<?php

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

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

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

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


Create new document fragment

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

DOMDocument::createDocumentFragment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createDocumentFragment — Create new document fragment

Beschreibung

public DOMDocument::createDocumentFragment(): DOMDocumentFragment

This function creates a new instance of class DOMDocumentFragment. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

The new DOMDocumentFragment.

Changelog

Version | Beschreibung
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

Beschreibung

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

This function creates a new instance of class DOMElement. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

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.

Rückgabewerte

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

Fehler/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

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

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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

Anmerkungen

Hinweis:

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

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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

Do this:

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

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

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

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

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

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

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

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

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

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

Here's the function:

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

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

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

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

<?php

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

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

    return $element;
}

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

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

$dom->appendChild($elm);

echo $dom->saveXML();

?>

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

<?php

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

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

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

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

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

print $doc->saveXML();
?>

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

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

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

    // @return  object  new element

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

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

    return $element;
  }
}

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

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

print $doc->saveXML();
?>

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

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

<?php

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

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

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

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

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

?>

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

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>
sergsokolenko at gmail dot com 30-Jan-2007 04:11
To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>


Create new element node with an associated namespace

  • « DOMDocument::createElement
  • DOMDocument::createEntityReference »
  • PHP Manual
  • DOMDocument
  • Create new element node with an associated namespace

DOMDocument::createElementNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElementNS — Create new element node with an associated namespace

Beschreibung

public DOMDocument::createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false

This function creates a new element node with an associated namespace. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

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.

Rückgabewerte

The new DOMElement or false if an error occurred.

Fehler/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).


Create new entity reference node

  • « DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction »
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7, PHP 8)

DOMDocument::createEntityReference — Create new entity reference node

Beschreibung

public DOMDocument::createEntityReference(string $name): DOMEntityReference|false

This function creates a new instance of class DOMEntityReference. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Rückgabewerte

The new DOMEntityReference or false if an error occurred.

Fehler/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

alicewonder at shastaherps dot org 24-Sep-2015 07:48
It appears that this does not work with numbered entities, only named entities.

$nbspace = $dom->createEntityReference('nbsp');

works

$nbspace = $dom->createEntityReference('#160');

does not. This makes this function rather useless when generating an XSL unless you modify the XSL doctype to include the named entity for the character you want.
Tuhin Bepari 04-Nov-2013 06:00
<?php
/*Entity is a group of words which print a special symbol.
Like if we want to show copy right symbol in html page then we use &copy; code and browser convert this to actual copyright symbol.
There have lots of entity, you can find them all form http://dev.w3.org/html5/html-author/charref
if you want to use < or > or both <> into a node value than xml will give and warning or make this value as a node.
So tell the xml parser that < or > is not tag symbol it is a entity.To do that you have to right &lt(<) and &gt;(>) instead of < and > symbol.

Entity references always begin with an ampersand (&) and end with a semicolon (;).
DO not need to use & and ; symbol begin and end of entity.Remove it when you want to use it to DOMDocument::createEntityReference
Then append to to a tag where you want to show this symbol.Like below
*/
$dom=new DOMDocument("1.0","UTF-8");
$example=$dom->createElement("example","This is copyright ");
$entity=$dom->createEntityReference("copy");
$example->appendChild($entity);
$dom->appendChild($example);
echo $dom->saveXML();

output is
This is copyright ©


Creates new PI node

  • « DOMDocument::createEntityReference
  • DOMDocument::createTextNode »
  • PHP Manual
  • DOMDocument
  • Creates new PI node

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7, PHP 8)

DOMDocument::createProcessingInstruction — Creates new PI node

Beschreibung

public DOMDocument::createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false

This function creates a new instance of class DOMProcessingInstruction. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

target

The target of the processing instruction.

data

The content of the processing instruction.

Rückgabewerte

The new DOMProcessingInstruction or false if an error occurred.

Fehler/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

romain at supinfo dot com 03-Feb-2009 11:57
A use exemple of this method :

Usefull for generating an XML linked with a XSLT !

<?php

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

//to have indented output, not just a line
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

// ------------- Interresting part here ------------

//creating an xslt adding processing line
$xslt = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');

//adding it to the xml
$xml->appendChild($xslt);

// ----------- / Interresting part here -------------

//adding some elements
$root = $xml->createElement("list");
$node = $xml->createElement("contact", "John Doe");
$root-> appendChild($node);
$xml-> appendChild($root);

//creating the file
$xml-> save("output.xml");

?>

output.xml :

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="base.xsl"?> //the line has been created successfully
<list>
  <contact>John Doe</contact>
</list>


Create new text node

  • « DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById »
  • PHP Manual
  • DOMDocument
  • Create new text node

DOMDocument::createTextNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::createTextNode — Create new text node

Beschreibung

public DOMDocument::createTextNode(string $data): DOMText

This function creates a new instance of class DOMText. Dieser Knoten wird im Dokument erst dann angezeigt, wenn er mit (z. B.) DOMNode::appendChild() eingefügt wird.

Parameter-Liste

data

The content of the text.

Rückgabewerte

The new DOMText.

Changelog

Version | Beschreibung
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

drewish at katherinehouse dot com 16-Dec-2014 10:03
The docs don't mention it but this method performs escaping on the value. If you don't want that use createElement() instead.
Alex Kaye 25-Jul-2009 07:04
A quick note to anyone who is using character entities (e.g. &copy;) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes.

Example:

<?php
$copyright_text_1 = $this->document->createTextNode("Copyright ");
$copyright_text_2 = $this->document->createTextNode(" Alex Kaye 2009");
$copyright_symbol = $this->document->createEntityReference("copy");
$copyright->appendChild($copyright_text_1);
$copyright->appendChild($copyright_symbol);
$copyright->appendChild($copyright_text_2);
?>


Searches for an element with a certain id

  • « DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName »
  • PHP Manual
  • DOMDocument
  • Searches for an element with a certain id

DOMDocument::getElementById

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementById — Searches for an element with a certain id

Beschreibung

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.

Parameter-Liste

elementId

The unique id value for an element.

Rückgabewerte

Returns the DOMElement or null if the element is not found.

Beispiele

Beispiel #1 DOMDocument::getElementById() Example

Die folgenden Beispiele verwenden book.xml mit dem folgenden Inhalt:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?php

$doc = new DomDocument;

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

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

The element whose id is 'php-basics' is: book

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

qualifiedName

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Rückgabewerte

A new DOMNodeList object containing all the matched elements.

Beispiele

Beispiel #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;
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

Siehe auch

  • 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

Beschreibung

public DOMDocument::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parameter-Liste

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.

Rückgabewerte

A new DOMNodeList object containing all the matched elements.

Changelog

Version | Beschreibung
8.0.3 | namespace is nullable now.

Beispiele

Beispiel #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";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

local name: include, prefix: xi
local name: fallback, prefix: xi

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

node

The node to import.

deep

If set to true, this method will recursively import the subtree under the node.

Hinweis:

To copy the nodes attributes deep needs to be set to true

Rückgabewerte

The copied node or false, if it cannot be copied.

Fehler/Exceptions

DOMException is thrown if node cannot be imported.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMDocument::load(string $filename, int $options = 0): bool

Loads an XML document from a file.

Warnung

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

Parameter-Liste

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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

Version | Beschreibung
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.

Beispiele

Beispiel #1 Creating a Document

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

Siehe auch

  • 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

Beschreibung

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.

Warnung

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.

Parameter-Liste

source

The HTML string.

options

Bitweises OR von libxml-Konstanten für weitere Optionen.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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.

Auch wenn fehlerhaftes HTML erfolgreich laden sollte, kann diese Funktion dennoch Fehler der Stufe E_WARNING generieren, wenn sie auf falsches Markup stößt. Die Fehlerbehandlungsfunktionen von libxml können genutzt werden, um diese Fehler zu behandeln.

Changelog

Version | Beschreibung
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.

Beispiele

Beispiel #1 Creating a Document

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

Siehe auch

  • 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

Beschreibung

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.

Warnung

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.

Parameter-Liste

filename

The path to the HTML file.

options

Bitweises OR von libxml-Konstanten für weitere Optionen.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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.

Auch wenn fehlerhaftes HTML erfolgreich laden sollte, kann diese Funktion dennoch Fehler der Stufe E_WARNING generieren, wenn sie auf falsches Markup stößt. Die Fehlerbehandlungsfunktionen von libxml können genutzt werden, um diese Fehler zu behandeln.

Changelog

Version | Beschreibung
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.

Beispiele

Beispiel #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Siehe auch

  • 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

Beschreibung

public DOMDocument::loadXML(string $source, int $options = 0): bool

Loads an XML document from a string.

Parameter-Liste

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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

Version | Beschreibung
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.

Beispiele

Beispiel #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Siehe auch

  • 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

Beschreibung

public DOMDocument::normalizeDocument(): void

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Siehe auch

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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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.

Achtung

The constructor of the objects of the registered node classes is not called.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Beispiel #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;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(9) "myElement"
text in child

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(13) "MyDOMDocument"
string(11) "DOMDocument"
string(18) "MyOtherDOMDocument"
string(18) "MyOtherDOMDocument"

Beispiel #4 Custom objects are transient

Achtung

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMDocument::relaxNGValidate(string $filename): bool

Performs » relaxNG validation on the document based on the given RNG schema.

Parameter-Liste

filename

The RNG file.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMDocument::relaxNGValidateSource(string $source): bool

Performs » relaxNG validation on the document based on the given RNG source.

Parameter-Liste

source

A string containing the RNG schema.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

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

Replaces the children in the document with new nodes.

Parameter-Liste

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Rückgabewerte

Returns the number of bytes written or false if an error occurred.

Beispiele

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

?>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

node

Optional parameter to output a subset of the document.

Rückgabewerte

Returns the HTML, or false if an error occurred.

Beispiele

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

?>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

filename

The path to the saved HTML document.

Rückgabewerte

Returns the number of bytes written or false if an error occurred.

Beispiele

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

?>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

Returns the XML, or false if an error occurred.

Fehler/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Changelog

Version | Beschreibung
8.3.0 | LIBXML_NOXMLDECL is now supported.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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>

Siehe auch

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

Beschreibung

public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool

Validates a document based on the given schema file.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool

Validates a document based on a schema defined in the given string.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben. If the document has no DTD attached, this method will return false.

Beispiele

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

Siehe auch

  • 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

Beschreibung

public DOMDocument::xinclude(int $options = 0): int|false

This method substitutes » XIncludes in a DOMDocument object.

Hinweis:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parameter-Liste

options

Bitweises OR von libxml-Konstanten für weitere Optionen.

Rückgabewerte

Returns the number of XIncludes in the document, -1 if some processing failed, or false if there were no substitutions.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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

Klassenbeschreibung

class DOMDocumentFragment extends DOMNode implements DOMParentNode {
/* Eigenschaften */
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Geerbte Eigenschaften */
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;
/* Methoden */
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
/* Geerbte Methoden */
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
}

Eigenschaften

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

Changelog

Version | Beschreibung
8.0.0 | The firstElementChild, lastElementChild, and childElementCount properties have been added.
8.0.0 | DOMDocumentFragment implements DOMParentNode now.

Inhaltsverzeichnis

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<hello/>beautiful<world/>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

data

XML to append.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMDocumentFragment::__construct()

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<hello/>beautiful<world/>

Siehe auch

  • 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

Beschreibung

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

Replaces the children in the document fragment with new nodes.

Parameter-Liste

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

beautiful
<world/>

Siehe auch

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

Einführung

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

Klassenbeschreibung

class DOMDocumentType extends DOMNode {
/* Eigenschaften */
public readonly string $name;
public readonly DOMNamedNodeMap $entities;
public readonly DOMNamedNodeMap $notations;
public readonly string $publicId;
public readonly string $systemId;
public readonly ?string $internalSubset;
/* Geerbte Eigenschaften */
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;
/* Geerbte Methoden */
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
}

Eigenschaften

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.


Die Klasse DOMElement

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* Eigenschaften */
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;
/* Geerbte Eigenschaften */
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;
/* Methoden */
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
/* Geerbte Methoden */
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
}

Eigenschaften

childElementCount

Die Anzahl der Kindelemente.

firstElementChild

Erstes Kindelement oder null.

lastElementChild

Letztes Kindelement oder null.

nextElementSibling

Das nächste Geschwisterelement oder null.

previousElementSibling

Das vorherige Geschwisterelement oder null.

schemaTypeInfo

Noch nicht implementiert, gibt immer null zurück

tagName

Der Name des Elements

className

Eine Zeichenkette, die die Klassen des Elements durch Leerzeichen getrennt darstellt

id

Die ID des Elements

Changelog

Version | Beschreibung
8.0.0 | Die Eigenschaften firstElementChild, lastElementChild, childElementCount, previousElementSibling, und nextElementSibling wurden hinzugefügt.
8.0.0 | DOMElement implementiert nun DOMParentNode und DOMChildNode.

Anmerkungen

Hinweis:

Die Erweiterung DOM verwendet die UTF-8 Kodierung. Es kann mb_convert_encoding(), UConverter::transcode() oder iconv() verwendet werden, um mit anderen Zeichenkodierungen zu arbeiten.

Inhaltsverzeichnis

  • 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

Beschreibung

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

Adds the passed nodes after the element.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Adds the passed nodes before the element.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

hello
<beautiful/>
<world/>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

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.

Beispiele

Beispiel #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> */

?>

Siehe auch

  • 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

Beschreibung

public DOMElement::getAttribute(string $qualifiedName): string

Gets the value of the attribute with name qualifiedName for the current node.

Parameter-Liste

qualifiedName

The name of the attribute.

Rückgabewerte

The value of the attribute, or an empty string if no attribute with the given qualifiedName is found.

Siehe auch

  • 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

Beschreibung

public DOMElement::getAttributeNames(): array

Get attribute names.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Return attribute names.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false

Returns the attribute node with name qualifiedName for the current element.

Parameter-Liste

qualifiedName

The name of the attribute.

Rückgabewerte

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

namespace

The namespace URI.

localName

The local name.

Rückgabewerte

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

namespace

The namespace URI.

localName

The local name.

Rückgabewerte

The value of the attribute, or an empty string if no attribute with the given localName and namespace is found.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

qualifiedName

The tag name. Use * to return all elements within the element tree.

Rückgabewerte

This function returns a new instance of the class DOMNodeList of all matched elements.

Siehe auch

  • 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

Beschreibung

public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

This function fetch all the descendant elements with a given localName and namespace.

Parameter-Liste

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.

Rückgabewerte

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

Version | Beschreibung
8.0.3 | namespace is nullable now.

Siehe auch

  • 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

Beschreibung

public DOMElement::hasAttribute(string $qualifiedName): bool

Indicates whether attribute named qualifiedName exists as a member of the element.

Parameter-Liste

qualifiedName

The attribute name.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMElement::hasAttributeNS(?string $namespace, string $localName): bool

Indicates whether attribute in namespace namespace named localName exists as a member of the element.

Parameter-Liste

namespace

The namespace URI.

localName

The local name.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

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

Inserts an element at a relative position given by where.

Parameter-Liste

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.

Rückgabewerte

Return DOMElement or null on failure.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Inserts text at a relative position given by where.

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

public DOMElement::remove(): void

Removes the element.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

public DOMElement::removeAttribute(string $qualifiedName): bool

Removes attribute named qualifiedName from the element.

Parameter-Liste

qualifiedName

The name of the attribute.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Siehe auch

  • 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

Beschreibung

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Removes attribute attr from the element.

Parameter-Liste

attr

The attribute node.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

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.

Siehe auch

  • 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

Beschreibung

public DOMElement::removeAttributeNS(?string $namespace, string $localName): void

Removes attribute localName in namespace namespace from the element.

Parameter-Liste

namespace

The namespace URI.

localName

The local name.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Siehe auch

  • 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

Beschreibung

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

Replaces the children in the element with new nodes.

Parameter-Liste

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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

Replaces the element with new nodes.

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn der Elternteil von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
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. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

qualifiedName

The name of the attribute.

value

The value of the attribute.

Rückgabewerte

The created or modified DOMAttr or false if an error occurred.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Beispiele

Beispiel #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

attr

The attribute node.

Rückgabewerte

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.

Fehler/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

attr

The attribute node.

Rückgabewerte

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.

Fehler/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

Siehe auch

  • 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

Beschreibung

public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void

Sets an attribute with namespace namespace and name qualifiedName to the given value. If the attribute does not exist, it will be created.

Parameter-Liste

namespace

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

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.

Siehe auch

  • 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

Beschreibung

public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void

Declares the attribute qualifiedName to be of type ID.

Parameter-Liste

qualifiedName

The name of the attribute.

isId

Set it to true if you want qualifiedName to be of type ID, false otherwise.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if qualifiedName is not an attribute of this element.

Siehe auch

  • 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

Beschreibung

public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void

Declares the attribute specified by attr to be of type ID.

Parameter-Liste

attr

The attribute node.

isId

Set it to true if you want name to be of type ID, false otherwise.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Siehe auch

  • 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

Beschreibung

public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void

Declares the attribute specified by qualifiedName and namespace to be of type ID.

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Siehe auch

  • 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

Beschreibung

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

Toggle the attribute.

Parameter-Liste

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.

Rückgabewerte

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

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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)

Einführung

This interface represents a known entity, either parsed or unparsed, in an XML document.

Klassenbeschreibung

class DOMEntity extends DOMNode {
/* Eigenschaften */
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;
/* Geerbte Eigenschaften */
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;
/* Geerbte Methoden */
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
}

Eigenschaften

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.


Die Klasse DOMEntityReference

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMEntityReference extends DOMNode {
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $name)
/* Geerbte Methoden */
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
}

Inhaltsverzeichnis

  • 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

Beschreibung

public DOMEntityReference::__construct(string $name)

Creates a new DOMEntityReference object.

Parameter-Liste

name

The name of the entity reference.

Beispiele

Beispiel #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> */

?>

Siehe auch

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


Die Klasse DOMException

(PHP 5, PHP 7, PHP 8)

Einführung

DOM-Operationen lösen unter bestimmten Umständen Ausnahmen aus, d. h., wenn eine Operation aus logischen Gründen nicht ausgeführt werden kann.

Siehe auch Exceptions (Ausnahmen).

Klassenbeschreibung

final class DOMException extends Exception {
/* Eigenschaften */
public int $code;
/* Geerbte Eigenschaften */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Geerbte Methoden */
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
}

Eigenschaften

code

Eine ganze Zahl, die die Art des erzeugten Fehlers angibt.

User Contributed Notes

There are no user contributed notes for this page.


The DOMImplementation class

(PHP 5, PHP 7, PHP 8)

Einführung

The DOMImplementation class provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Klassenbeschreibung

class DOMImplementation {
/* Methoden */
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
}

Inhaltsverzeichnis

  • 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;
        /* [...] */
    }

?>


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

Beschreibung

DOMImplementation::__construct()

Creates a new DOMImplementation object.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

A new DOMDocument object or false on error. If namespace, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Fehler/Exceptions

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

Version | Beschreibung
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.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Rückgabewerte

A new DOMDocumentType node with its ownerDocument set to null or false on error.

Fehler/Exceptions

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

Changelog

Version | Beschreibung
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Beispiele

Beispiel #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'
);

$implementation = new DOMImplementation;

foreach ($features as $key => $name) {
if ($implementation->hasFeature($key, '2.0')) {
echo "Has feature $name\n";
} else {
echo "Missing feature $name\n";
}
}

?>

Siehe auch

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

Klassenbeschreibung

class DOMNamedNodeMap implements IteratorAggregate, Countable {
/* Eigenschaften */
public readonly int $length;
/* Methoden */
public count(): int
public getIterator(): Iterator
public getNamedItem(string $qualifiedName): ?DOMNode
public getNamedItemNS(?string $namespace, string $localName): ?DOMNode
public item(int $index): ?DOMNode
}

Eigenschaften

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

Version | Beschreibung
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.

Inhaltsverzeichnis

  • 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

Beschreibung

public DOMNamedNodeMap::count(): int

Gets the number of nodes in the map.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Eine Instanz eines Objektes, das Iterator oder Traversable implementiert.

Fehler/Exceptions

Wirft im Fehlerfall eine Exception.

Siehe auch

  • IteratorAggregate::getIterator() - Ruft einen externen Iterator ab

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

Beschreibung

public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode

Retrieves a node specified by its nodeName.

Parameter-Liste

qualifiedName

The nodeName of the node to retrieve.

Rückgabewerte

A node (of any type) with the specified nodeName, or null if no node is found.

Siehe auch

  • 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

Beschreibung

public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode

Retrieves a node specified by localName and namespace.

Parameter-Liste

namespace

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Rückgabewerte

A node (of any type) with the specified local name and namespace URI, or null if no node is found.

Siehe auch

  • 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
  • DOMNameSpaceNode »
  • 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

Beschreibung

public DOMNamedNodeMap::item(int $index): ?DOMNode

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parameter-Liste

index

Index into this map.

Rückgabewerte

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

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMNameSpaceNode {
/* Eigenschaften */
public readonly string $nodeName;
public readonly ?string $nodeValue;
public readonly int $nodeType;
public readonly string $prefix;
public readonly ?string $localName;
public readonly ?string $namespaceURI;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
}

Eigenschaften

nodeName

The qualified name of this node.

nodeValue

The namespace URI declared by this node, or null if the empty namespace.

nodeType

The type of the node. In this case it returns XML_NAMESPACE_DECL_NODE .

prefix

The namespace prefix declared by this node.

localName

The local part of the qualified name of this node.

namespaceURI

The namespace URI declared by this node, or null if it is unspecified.

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

parentNode

The parent of this node. If there is no such node, this returns null.

parentElement

The parent element of this node. If there is no such element, this returns null.

Changelog

Version | Beschreibung
8.3.0 | Properties DOMNameSpaceNode::$parentElement, and DOMNameSpaceNode::$isConnected have been added.

User Contributed Notes

There are no user contributed notes for this page.


The DOMNode class

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMNode {
/* Eigenschaften */
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;
/* Methoden */
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
}

Eigenschaften

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

Version | Beschreibung
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.

Anmerkungen

Hinweis:

Die Erweiterung DOM verwendet die UTF-8 Kodierung. Es kann mb_convert_encoding(), UConverter::transcode() oder iconv() verwendet werden, um mit anderen Zeichenkodierungen zu arbeiten.

Siehe auch

  • » W3C specification of Node

Inhaltsverzeichnis

  • DOMNode::appendChild — Adds new child at the end of the children
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::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.


Adds new child at the end of the children

  • « DOMNode
  • DOMNode::C14N »
  • PHP Manual
  • DOMNode
  • Adds new child at the end of the children

DOMNode::appendChild

(PHP 5, PHP 7, PHP 8)

DOMNode::appendChild — Adds new child at the end of the children

Beschreibung

public DOMNode::appendChild(DOMNode $node): DOMNode|false

This function appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument::createElement(), DOMDocument::createTextNode() etc. or simply by using any other node.

When using an existing node it will be moved.

Parameter-Liste

node

The appended child.

Rückgabewerte

The node added or false on error.

Fehler/Exceptions

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.

Beispiele

The following example will add a new element node to a fresh document.

Beispiel #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Beispiel #2 Nested children

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

Siehe auch

  • 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

Beschreibung

public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false

Canonicalize nodes to a string

Parameter-Liste

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.

Rückgabewerte

Returns canonicalized nodes as a stringBei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false

Canonicalize nodes to a file.

Parameter-Liste

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.

Rückgabewerte

Number of bytes writtenBei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMNode::cloneNode(bool $deep = false): DOMNode|false

Creates a copy of the node.

Parameter-Liste

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to false.

Rückgabewerte

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

Beschreibung

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

Checks if node contains other node.

Parameter-Liste

other

Node to be checked.

Rückgabewerte

Returns true if node contains other node, false otherwise.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMNode::getLineNo(): int

Gets line number for where the node was defined at parse time.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the line number where the node was defined at parse time. If the node was created manually, the return value will be 0.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMNode::getNodePath(): ?string

Gets an XPath location path for the node.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns a string containing the XPath, or null in case of an error.

Beispiele

Beispiel #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";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

Siehe auch

  • 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

Beschreibung

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

Get root node.

Parameter-Liste

options

This parameter has no effect yet.

Rückgabewerte

Returns the root node.

Beispiele

Beispiel #1 DOMNode::getRootNode() example

<?php

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMNode::hasAttributes(): bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMNode::hasChildNodes(): bool

This function checks if the node has children.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

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.

Parameter-Liste

node

The new node.

child

The reference node. If not supplied, node is appended to the children.

Rückgabewerte

The inserted node or false on error.

Fehler/Exceptions

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.

Siehe auch

  • DOMNode::appendChild() - Adds new child at the end of the children

User Contributed Notes

jarry1250 at gmail dot com 30-May-2015 01:59
Note that supplying the same node for $newnode and $refnode leads to an E_WARNING ("Couldn't add newnode as the previous sibling of refnode"). For example imagine one wanted to make $newnode the first child of its parent by doing:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Bad:
$newnode->parentNode->insertBefore( $newnode, $firstSibling );
?>

This would generate a warning if it already was the first child of its parent, since $newnode and $firstSibling are identical. Easy to work around though:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Better:
if( $newnode !== $firstSibling ) {
    $newnode->parentNode->insertBefore( $newnode, $firstSibling );
}
?>
DrTebi at Yahoo 03-Oct-2007 05:54
Sorry, my previous posting worked only for the top node. Here the corrected version, which will work for any node:

XML
----
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>Thomas</person>
</contacts>

PHP
---
<?php
// load XML, create XPath object
$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
$xpath = new DOMXPath($xml);

// get node eva, which we will append to
$eva = $xpath->query('/contacts/person[.="Eva"]')->item(0);

// create node john
$john = $xml->createElement('person', 'John');

// insert john after eva
//   "in eva's parent node (=contacts) insert
//   john before eva's next node"
// this also works if eva would be the last node
$eva->parentNode->insertBefore($john, $eva->nextSibling);

// show result
header('Content-Type: text/plain');
print $xml->saveXML();
?>

Result
------
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person><person>John</person>
  <person>Thomas</person>
</contacts>
justin at redwiredesign dot com 07-Feb-2007 08:20
The previous example is incorrect, and causes a DOM_NOT_FOUND error, as the child nodes are not direct descendants of the root node.

Therefore, the line:

$parent_path = "/root";

needs to change to:

$parent_path = "/root/parent";

or

$parent_path = "//parent";

for this example to work
jg at handcode dot de 18-Aug-2005 12:18
example to insert <newnode/> between <chid1/> and <child2/>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
  <parent>
    <child nr="1"/>
    <child nr="2"/>
  </parent>
</root>

<?php

$xml_src = 'test.xml';

// XPath-Querys
$parent_path = "//parent";
$next_path = "//parent/child[@nr='2']";

// Create a new DOM document
$dom = new DomDocument();
$dom->load($xml_src);

// Find the parent node
$xpath = new DomXPath($dom);

// Find parent node
$parent = $xpath->query($parent_path);

// new node will be inserted before this node
$next = $xpath->query($next_path);

// Create the new element
$element = $dom->createElement('newnode');

// Insert the new element
$parent->item(0)->insertBefore($element, $next->item(0));

echo $dom->saveXML();

?>
Jerry Ellis 03-Jun-2005 12:45
1st argument) a node to insert
2nd argument) a reference node - this is the node that the new node will be inserted before

The trick to using this method is that the OBJECT on which you actually CALL the insertBefore() method is actually the PARENT node of the reference node!

INCORRECT:
$DOMNode_refNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);

CORRECT:
$DOMNode_refNode->parentNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);


Checks if the specified namespaceURI is the default namespace or not

  • « DOMNode::insertBefore
  • DOMNode::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

Beschreibung

public DOMNode::isDefaultNamespace(string $namespace): bool

Tells whether namespace is the default namespace.

Parameter-Liste

namespace

The namespace URI to look for.

Rückgabewerte

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

Beschreibung

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

Checks that both nodes are equal.

Parameter-Liste

otherNode

The node.

Rückgabewerte

Returns true if both nodes are equal, false otherwise.

Beispiele

Beispiel #1 DOMNode::isEqualNode() example

<?php

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beschreibung

public DOMNode::isSameNode(DOMNode $otherNode): bool

This function indicates if two nodes are the same node. The comparison is not based on content

Parameter-Liste

otherNode

The compared node.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

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

Beschreibung

public DOMNode::isSupported(string $feature, string $version): bool

Checks if the asked feature is supported for the specified version.

Parameter-Liste

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.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • 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

Beschreibung

public DOMNode::lookupNamespaceURI(?string $prefix): ?string

Gets the namespace URI of the node based on the prefix.

Parameter-Liste

prefix

The prefix to look for. If this parameter is null, the method will return the default namespace URI, if any.

Rückgabewerte

Returns the associated namespace URI or null if none is found.

Siehe auch

  • 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

Beschreibung

public DOMNode::lookupPrefix(string $namespace): ?string

Gets the namespace prefix of the node based on the namespace URI.

Parameter-Liste

namespace

The namespace URI.

Rückgabewerte

The prefix of the namespace or null on error.

Siehe auch

  • 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

Beschreibung

public DOMNode::normalize(): void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Siehe auch

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

Beschreibung

public DOMNode::removeChild(DOMNode $child): DOMNode|false

This functions removes a child from a list of children.

Parameter-Liste

child

The removed child.

Rückgabewerte

If the child could be removed the function returns the old child or false on error.

Fehler/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if child is not a child of this node.

Beispiele

The following example will delete the chapter element of our XML document.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • DOMChildNode::remove() - Removes the node
  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

nggit@phpindonesia 01-Feb-2019 02:29
You can use foreach to remove multiple elements from a DOMNodeList, only if you use a temporary array or via XPath query.
If not, the simplest way will be:

<?php

while ($element = $nodeList->item(0)) {
    $element->parentNode->removeChild($element);
}

?>
Kenney 28-Mar-2013 10:19
This method will remove all child nodes but leave the attributes (and namespace declarations) intact.

<?php
function removeChildren( &$node )
{
  $node->parentNode->replaceChild(
    $n = $node->cloneNode( false ),
    $node );

  $node = $n;
}
?>
drimsun at gmail dot com 11-Feb-2010 03:37
If you try to remove children of a nested node (e.g. a <ul> list that contains another <ul>) and only remove the first level of child nodes, you'll get a messed-up node object.

Upon re-use of the messed-up node you'll get an error message that says: "Fatal error: Call to a member function blahblah() on a non-object".

To remove ALL child nodes, use this recursive function instead:
<?php
/**
 * Helper function that removes all child nodes of $node recursively
 * (i.e. including child nodes of the child nodes and so forth).
 */
function remove_children(&$node) {
  while ($node->firstChild) {
    while ($node->firstChild->firstChild) {
      remove_children($node->firstChild);
    }
    $node->removeChild($node->firstChild);
  }
}
?>
Justin Carlson 05-Nov-2009 11:46
Just a note, if you remove a node the whitespace it occupied will remain if you save the file.

To avoid this, use $document->preserveWhiteSpace = false;

For Example:

<?php
$document = new DomDocument();
$document->preserveWhiteSpace = false;
?>
crazy888s at hotmail dot com 15-Apr-2009 01:50
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
  //  ...do stuff with $domElement...
  $domElement->parentNode->removeChild($domElement);
}
?>

... will seemingly leave the internal iterator on the foreach out of wack and results will be quite strange. Though, making a queue of items to remove seems to work. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
  // ...do stuff with $domElement...
  $domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
  $domElement->parentNode->removeChild($domElement);
}
?>
Justin Sheckler 30-Jan-2009 08:44
These two functions might be helpful to anyone trying to delete a node and all of its children:

<?php
function deleteNode($node) {
    deleteChildren($node);
    $parent = $node->parentNode;
    $oldnode = $parent->removeChild($node);
}

function deleteChildren($node) {
    while (isset($node->firstChild)) {
        deleteChildren($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}
?>
tim cameron ryan 19-Jul-2008 01:00
Or something like:

<?php

while ($node->childNodes->length)
     $node->removeChild($node->firstChild);

?>
Michael D (DigitalGemstones.com) 05-Jul-2008 04:15
Note that iterating through the childNodes array and removing those children will stop the iteration.

For example:
<?php
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
     $child->parentNode->removeChild($child);
}
?>

Will not work.  Note that in removing the node, the childNodes array gets rebuilt (it seems) and so only the first item will be removed.  In order to properly remove all the children you want to remove, you will need to do something like the following:

<?php
$nodesToDelete = array();
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
    $nodesToDelete[] = $child;
}
foreach($nodesToDelete as $node)
{
  $node->parentNode->removeChild($node);
}
?>

I believe this is actually more efficient than the first snippet would be (if it worked) but obviously I cannot benchmark it.
Wala 04-Apr-2008 10:57
I used the following to delete an entire node using the child element:

<?php
$childElement->parentNode->parentNode-> removeChild($childElement->parentNode);
?>

I could not have thought of it without the help of everyone who contributed to this thread.

Thanks!

(I had to introduce the extra space between parentNode->removeChild to get rid of the wordwrap() warning while posting this note)
Vasil Rangelov 06-Oct-2007 10:14
At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.

The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.
mytto at openxtrem dot com 07-Sep-2005 02:20
Back again on removing childs and iterators robustness.

Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.

The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!

The following piece of code will, for instance, remove all empty child nodes:

<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
  $childNodes[] = $childNode;
}

// Browse with the copy
foreach ($childNodes as $childNode) {
  if (!$childNode->hasChildNodes()); {
    $childNode->parentNode->removeChild($childNode);
  }
}
?>
blaine (at) blainegarrett (dot com) 23-Aug-2005 10:10
This might be obvious, but might help someone as well...

If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...

$node->parentNode->removeChild($node);

parentNode is a scalar property of the Element.

Hope that helps.

--
Blaine Garrett
pedro at leb dot usp dot br 30-May-2005 04:24
You may also use the hasChild function:
<?php

while($node->hasChildNodes()) {
  $node->removeChild($node->childNodes->item(0));
}

?>

When you remove a childNode, the next node becomes the first one!
vsematika at centrum dot cz 13-Feb-2005 03:35
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:

First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
   $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.

The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:

<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
   $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>


Replaces a child

  • « DOMNode::removeChild
  • DOMNodeList »
  • PHP Manual
  • DOMNode
  • Replaces a child

DOMNode::replaceChild

(PHP 5, PHP 7, PHP 8)

DOMNode::replaceChild — Replaces a child

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

The old node or false if an error occur.

Fehler/Exceptions

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.

Siehe auch

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

User Contributed Notes

chealer at gmail dot com 15-Aug-2018 03:07
As of version 5.6, PHP still behaves as reported by jb at jbpros dot com. To use replaceChild() in a loop, the more standard pattern used in the following example can be used:

for ($currentNode = 0; $currentNode < $link->childNodes->length; $currentNode++) {
    $child = $link->childNodes[$currentNode];

    // "Remove" links, since links can't contain links
    if ($child instanceof DOMElement && $child->tagName == 'a') {
        $replacement = $dom->createTextNode($child->textContent);
        $link->replaceChild($replacement, $child);
    }
}
jb at jbpros dot com 01-Mar-2005 08:08
If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList.  If the old node has a different name from the new node, it will be removed from the list once it has been replaced.  Use a regressive loop:

<?php

$xml = new DOMDocument;
$xml->load('docfile.xml');

$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
    $element = $elements->item($i);
    $ignore = false;

    $newelement = $xml>createTextNode('Some new node!');
    $element->parentNode->replaceChild($newelement, $element);
    $i--;
}

?>

The loop counter ($i) will always be in the list's interval as removed elements indexes are above the counter.
aidan at php dot net 26-Dec-2004 02:17
Here is a simple example for replacing a node:

Let's define our XML like so:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
  <parent>
     <child>bar</child>
     <child>foo</child>
  </parent>
</root>
XML;
?>

If we wanted to replace the entire <parent> node, we could do something like this:

<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');

// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child', 'anothervalue'));

// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>

Next, we need to locate the old node:

<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);

// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>

We then import and replace the new node:

<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);

// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);

// Display
echo $dom->saveXML();
?>

Our new node is successfully imported:

<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
franp at free dot fr 23-Sep-2004 08:39
1) If your XPath query returns a NodeList including a unique item, or if you know for sure the order of the items returned, you can use the "item(n)" syntax instead of the "foreach" syntax.
This can greatly improve you code lisibility.
s the method name implies, replaceChild cannot replace a node itself but a child of a node.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
 <actionGlobal>
  <actionGlobalFR>sometext</actionGlobalFR>
 <actionGlobal>
</action>

$frag = $doc->createElement("actionGlobalFR");
$fragA = $doc->createTextNode("anothertext");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/actionGlobal/actionGlobalFR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($ajout, $xpResult->item(0));

2) Also, as the method name implies, replaceChild cannot replace a node itself but a child of a node.
Still it is possible to replace a node pointed by XPath istead of its child.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
  <FR>French Text</FR>
</action>

<?php
$frag = $doc->createElement("EN");
$fragA = $doc->createTextNode("English Text");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/FR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($fragA, $xpResult->item(0));
?>

Et voil? !

This produces :
<?xml version="1.0" ?>
<action>
  <EN>English Text</EN>
</action>

....................................................

3) Also, be carefull, you CANNOT replace a node that doesn't exist.
While this may seems obvious, it is easy to forget.

Consider this :
<?xml version="1.0" ?>
<action>
  <EN></EN>
</action>

You cannot use replaceChild() to turn this into :
<?xml version="1.0" ?>
<action>
  <EN>Some text</EN>
</action>

The reason is that since the <EN></EN> element is empty, it has no child (this is clearer to understand if you consider that <EN></EN> can be written <EN />).
The fact that you intend to put some text inbetween <EN> and </EN> does not change the fact that it has no text yet, thus no child yet.
When dealing with DOM, do not take your dream for the reality. The DOM parser doen't care about your dreams. If an element is currently empty, it has no child, whatever you intend to fill in.

Thus, the solution to teh problem is to use appendChild intead of replaceChild :

<?php
$fragA = $doc->createTextNode("Some Text");
$xpResult = $xp->query("/action/EN");
$blipblip = $xpResult->item(0)->appendChild($fragA);
?>

This produces the awaited :
<?xml version="1.0" ?>
<action>
  <EN>Some Text</EN>
</action>

....................................................

4) Note that the description of replaceChild in the doc is wrong. Arguments have been inverted.
The correct description is :
object DOMNode->replaceChild (object newnode, object oldnode)


The DOMNodeList class

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMNodeList implements IteratorAggregate, Countable {
/* Eigenschaften */
public readonly int $length;
/* Methoden */
public count(): int
public getIterator(): Iterator
public item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null
}

Eigenschaften

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

Version | Beschreibung
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.

Siehe auch

  • » W3C specification of NodeList

Inhaltsverzeichnis

  • 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

Beschreibung

public DOMNodeList::count(): int

Gets the number of nodes in the list.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Eine Instanz eines Objektes, das Iterator oder Traversable implementiert.

Fehler/Exceptions

Wirft im Fehlerfall eine Exception.

Siehe auch

  • IteratorAggregate::getIterator() - Ruft einen externen Iterator ab

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

Beschreibung

public DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retrieves a node specified by index within the DOMNodeList object.

Tipp

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parameter-Liste

index

Index of the node into the collection.

Rückgabewerte

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

Beispiele

Beispiel #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";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

?>


Die Klasse DOMNotation

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMNotation extends DOMNode {
/* Eigenschaften */
public readonly string $publicId;
public readonly string $systemId;
/* Geerbte Eigenschaften */
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;
/* Geerbte Methoden */
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
}

Eigenschaften

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


The DOMParentNode interface

(PHP 8)

Interface-Übersicht

interface DOMParentNode {
/* Methoden */
public append(DOMNode|string ...$nodes): void
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Siehe auch

  • 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

Beschreibung

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

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

Parameter-Liste

nodes

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

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Siehe auch

  • 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

Beschreibung

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

Replace children in node.

Parameter-Liste

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Fehler/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Wird ausgelöst, wenn dieser Knoten von einem Typ ist, der keine Kinder vom Typ eines der übergebenen nodes zulässt, oder wenn der einzufügende Knoten einer der Vorfahren dieses Knotens oder dieser Knoten selbst ist.

DOM_WRONG_DOCUMENT_ERR

Wird ausgelöst, wenn einer der übergebenen nodes aus einem anderen Dokument erstellt wurde als dem, das diesen Knoten erstellt hat.

Changelog

Version | Beschreibung
8.3.0 | Calling this method on a node without an owner document now works. Zuvor führte dies zu einer DOMException mit dem Code DOM_HIERARCHY_REQUEST_ERR.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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


Die Klasse DOMProcessingInstruction

(PHP 5, PHP 7, PHP 8)

Klassenbeschreibung

class DOMProcessingInstruction extends DOMNode {
/* Eigenschaften */
public readonly string $target;
public string $data;
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $name, string $value = "")
/* Geerbte Methoden */
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
}

Eigenschaften

target

data

Inhaltsverzeichnis

  • 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

Beschreibung

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.

Parameter-Liste

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

Siehe auch

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

Einführung

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Klassenbeschreibung

class DOMText extends DOMCharacterData {
/* Eigenschaften */
public readonly string $wholeText;
/* Geerbte Eigenschaften */
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;
/* Methoden */
public __construct(string $data = "")
public isElementContentWhitespace(): bool
public isWhitespaceInElementContent(): bool
public splitText(int $offset): DOMText|false
/* Geerbte Methoden */
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
}

Eigenschaften

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Changelog

Version | Beschreibung
8.0.0 | The unimplemented method DOMText::replaceWholeText() has been removed.

Inhaltsverzeichnis

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Breaks this node into two nodes at the specified offset

User Contributed Notes

Trititaty 20-Oct-2016 11:47
Text replacement function for DOM.

<?php
function domTextReplace( $search, $replace, DOMNode &$domNode, $isRegEx = false ) {
  if ( $domNode->hasChildNodes() ) {
    $children = array();
    // since looping through a DOM being modified is a bad idea we prepare an array:
    foreach ( $domNode->childNodes as $child ) {
      $children[] = $child;
    }
    foreach ( $children as $child ) {
      if ( $child->nodeType === XML_TEXT_NODE ) {
        $oldText = $child->wholeText;
        if ( $isRegEx ) {
          $newText = preg_replace( $search, $replace, $oldText );
        } else {
          $newText = str_replace( $search, $replace, $oldText );
        }
        $newTextNode = $domNode->ownerDocument->createTextNode( $newText );
        $domNode->replaceChild( $newTextNode, $child );
      } else {
        domTextReplace( $search, $replace, $child, $isRegEx );
      }
    }
  }
}


Creates a new DOMText object

  • « DOMText
  • DOMText::isElementContentWhitespace »
  • PHP Manual
  • DOMText
  • Creates a new DOMText object

DOMText::__construct

(PHP 5, PHP 7, PHP 8)

DOMText::__construct — Creates a new DOMText object

Beschreibung

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

Creates a new DOMText object.

Parameter-Liste

data

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

Beispiele

Beispiel #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> */

?>

Siehe auch

  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Thomas 27-Apr-2012 01:54
I experinced that DOMText, given a integer as only value to the constructor failed to return valid data. I had to typecast the input to a string first:

$intValue = 3252; // Post/Zip-code
$some_element->appendChild( new DOMText( (string) $intValue) );

When not typecasting using "(string)" the XML output from $root->saveXML() would not validate.


Returns whether this text node contains whitespace in element content

  • « DOMText::__construct
  • DOMText::isWhitespaceInElementContent »
  • PHP Manual
  • DOMText
  • Returns whether this text node contains whitespace in element content

DOMText::isElementContentWhitespace

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

DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content

Beschreibung

public DOMText::isElementContentWhitespace(): bool

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

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

Beschreibung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns true if node contains zero or more whitespace characters and nothing else. Returns false otherwise.

User Contributed Notes

JITR 07-Jul-2007 03:36
To add to `permidion at yahoo dot com''s comment:

Quite true. According to DOM Level 3 Core, the `isWhitespaceInElementContent()' method indicates, whether the node contains `whitespace in element content' (or `element content whitespace' according to the newer spec), see [1].

Btw, it seems the `isWhitespaceInElementContent()' method was replaced with the `isElementContentWhitespace' attribute in the current W3C recommendation, see [2].

I have the feeling, though, it would be more precise with the word `only' added, like: `... indicates, whether the node contains *only* element content whitespace.' This would better correspond with the fact the result is false, when there are any non-whitespace characters present (in addition to the whitespace ones), as already noted.

[1] (please concatenate the following two lines)
http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html
#core-Text3-isWhitespaceInElementContent
[2] (please concatenate the following two lines)
http://www.w3.org/TR/DOM-Level-3-Core/core.html
#Text3-isElementContentWhitespace
permidion at yahoo dot com 28-Oct-2004 08:30
if you have an xml element such as <name>Foo Bar</name> (note the space), isWhitespaceInElementContent will return false.
However it will return true for <name><name> or <name/>
so, that function can be used to determine if the element has a text content or not


Breaks this node into two nodes at the specified offset

  • « DOMText::isWhitespaceInElementContent
  • DOMXPath »
  • PHP Manual
  • DOMText
  • Breaks this node into two nodes at the specified offset

DOMText::splitText

(PHP 5, PHP 7, PHP 8)

DOMText::splitText — Breaks this node into two nodes at the specified offset

Beschreibung

public DOMText::splitText(int $offset): DOMText|false

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parameter-Liste

offset

The offset at which to split, starting from 0.

Rückgabewerte

The new node of the same type, which contains all the content at and after the offset.

User Contributed Notes

Flix Cloutier 28-Oct-2013 05:31
It should be noted that $offset is a **character offset**, not a **byte offset**. This means that most other PHP string functions that deal with lengths and offsets (strlen, strpos, preg_match with PREG_OFFSET_CAPTURE, etc.) use and return values unsuitable for this method if used with multibyte strings (like UTF-8 strings).

Byte offsets can be converted to character offsets with mb_strlen:

<?php
function char_offset($string, $byte_offset, $encoding = null)
{
    $substr = substr($string, 0, $byte_offset);
    return mb_strlen($substr, $encoding ?: mb_internal_encoding());
}
?>


Die Klasse DOMXPath

(PHP 5, PHP 7, PHP 8)

Einführung

Unterstützt XPath 1.0

Klassenbeschreibung

class DOMXPath {
/* Eigenschaften */
public readonly DOMDocument $document;
public bool $registerNodeNamespaces;
/* Methoden */
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
}

Eigenschaften

document

registerNodeNamespaces

Wenn auf true gesetzt, werden die Namensräume des Knotens registriert.

Changelog

Version | Beschreibung
8.0.0 | Die Eigenschaft registerNodeNamespaces wurde hinzugefügt.

Inhaltsverzeichnis

  • 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

Beschreibung

public DOMXPath::__construct(DOMDocument $document, bool $registerNodeNS = true)

Creates a new DOMXPath object.

Parameter-Liste

document

The DOMDocument associated with the DOMXPath.

registerNodeNS

Legt fest, ob die Namensraum-Präfixe innerhalb des Geltungsbereichs des Kontextknotens automatisch im DOMXPath-Objekt registriert werden sollen. Dies kann verwendet werden, damit DOMXPath::registerNamespace() nicht manuell für jeden Namensraum innerhalb des Geltungsbereichs aufgerufen werden muss. Wenn es einen Konflikt zwischen Namensraum-Präfixen gibt, wird nur das in der Reihenfolge nächste Namensraum-Präfix registriert.

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

Beschreibung

public DOMXPath::evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression and returns a typed result if possible.

Parameter-Liste

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

Legt fest, ob die Namensraum-Präfixe innerhalb des Geltungsbereichs des Kontextknotens automatisch im DOMXPath-Objekt registriert werden sollen. Dies kann verwendet werden, damit DOMXPath::registerNamespace() nicht manuell für jeden Namensraum innerhalb des Geltungsbereichs aufgerufen werden muss. Wenn es einen Konflikt zwischen Namensraum-Präfixen gibt, wird nur das in der Reihenfolge nächste Namensraum-Präfix registriert.

Rückgabewerte

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.

Beispiele

Beispiel #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";

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

There are 2 english books

Siehe auch

  • 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

Beschreibung

public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression.

Parameter-Liste

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

Legt fest, ob die Namensraum-Präfixe innerhalb des Geltungsbereichs des Kontextknotens automatisch im DOMXPath-Objekt registriert werden sollen. Dies kann verwendet werden, damit DOMXPath::registerNamespace() nicht manuell für jeden Namensraum innerhalb des Geltungsbereichs aufgerufen werden muss. Wenn es einen Konflikt zwischen Namensraum-Präfixen gibt, wird nur das in der Reihenfolge nächste Namensraum-Präfix registriert.

Rückgabewerte

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.

Beispiele

Beispiel #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";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Siehe auch

  • 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

Beschreibung

public DOMXPath::registerNamespace(string $prefix, string $namespace): bool

Registers the namespace and prefix with the DOMXPath object.

Parameter-Liste

prefix

The prefix.

namespace

The URI of the namespace.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

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 Funktionen »
  • 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

Beschreibung

public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void

This method enables the ability to use PHP functions within XPath expressions.

Parameter-Liste

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.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

The following examples use book.xml which contains the following:

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

Beispiel #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";
}

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Beispiel #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";
}

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Books with multiple authors:
PHP Basics

Siehe auch

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

Inhaltsverzeichnis

  • dom_import_simplexml — Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt

User Contributed Notes

There are no user contributed notes for this page.


Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt

  • « DOM Funktionen
  • libxml »
  • PHP Manual
  • DOM Funktionen
  • Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt

dom_import_simplexml

(PHP 5, PHP 7, PHP 8)

dom_import_simplexml — Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt

Beschreibung

dom_import_simplexml(object $node): DOMElement

Diese Funktion verwendet den Knoten node der Klasse SimpleXML und macht ihn zu einem DOMElement-Knoten. Dieses neue Objekt kann als nativer DOMElement-Knoten verwendet werden..

Parameter-Liste

node

Der SimpleXMLElement-Knoten.

Rückgabewerte

Der hinzugefügte DOMElement-Knoten.

Changelog

Version | Beschreibung
8.0.0 | Diese Funktion gibt im Fehlerfall nicht mehr null zurück.

Beispiele

Beispiel #1 Importiert SimpleXML in DOM mit der Funktion dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
echo 'Fehler beim Parsen des Dokumentes';
exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Fehler bei Konvertierung zu XML';
exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Siehe auch

  • simplexml_import_dom() - Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten

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

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation for PHP versions >= 7.4
    • Installation for PHP versions < 7.4
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • LibXMLError — The LibXMLError class
  • libxml Funktionen
    • libxml_clear_errors — Clear libxml error buffer
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Retrieve array of errors
    • libxml_get_external_entity_loader — Get the current external entity loader
    • libxml_get_last_error — Retrieve last error from libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


Einführung

These functions/constants are available as of PHP 5.1.0, and the following core extensions rely on this libxml extension: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC und XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


Installation/Konfiguration

Inhaltsverzeichnis

  • Anforderungen
  • Installation for PHP versions >= 7.4
  • Installation for PHP versions < 7.4
  • Laufzeit-Konfiguration
  • Ressource-Typen

User Contributed Notes

There are no user contributed notes for this page.


Anforderungen

This extension requires » libxml >= 2.9.0 as of PHP 8.0. libxml >= 2.6.0 prior to PHP 8.0.

User Contributed Notes

There are no user contributed notes for this page.


Installation for PHP versions >= 7.4

The libxml extension is enabled by default, although it may be disabled with --without-libxml.

PHP uses pkg-config to select the right library file, header files, and compile flags to use for libxml2. To ensure that the desired version of libxml2 is selected, the PKG_CONFIG_PATH environment variable may be used to control the search path for pkg-config prior to running the configure script:

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.


Installation for PHP versions < 7.4

The libxml extension is enabled by default, although it may be disabled with --disable-libxml.

The optional --with-libxml-dir directive is used to specify the location of libxml on the system that PHP is being compiled on, otherwise only the default locations are scanned. The configure process checks for libxml (specifically, xml2-config) in the following order:

  1. The location ([DIR]) specified with --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

If configure cannot find xml2-config in the directory specified by --with-libxml-dir, then it'll continue on and check the default locations.

User Contributed Notes

There are no user contributed notes for this page.


Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

LIBXML_BIGLINES (int)
Allows line numbers greater than 65535 to be reported correctly.

Hinweis:

Only available as of PHP 7.0.0 with Libxml >= 2.9.0

LIBXML_COMPACT (int)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Hinweis:

Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (int)
Default DTD attributes
LIBXML_DTDLOAD (int)
Load the external subset
LIBXML_DTDVALID (int)
Validate with the DTD
Achtung

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

LIBXML_HTML_NOIMPLIED (int)
Sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements.

Hinweis:

Only available in Libxml >= 2.7.7 (as of PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (int)
Sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.

Hinweis:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

LIBXML_NOBLANKS (int)
Remove blank nodes
LIBXML_NOCDATA (int)
Merge CDATA as text nodes
LIBXML_NOEMPTYTAG (int)
Expand empty tags (e.g. <br/> to <br></br>)

Hinweis:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (int)
Substitute entities
Achtung

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

LIBXML_NOERROR (int)
Suppress error reports
LIBXML_NONET (int)
Disable network access when loading documents
LIBXML_NOWARNING (int)
Suppress warning reports
LIBXML_NOXMLDECL (int)
Drop the XML declaration when saving a document

Hinweis:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (int)
Remove redundant namespace declarations
LIBXML_PARSEHUGE (int)
Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document or the entity recursion, as well as limits of the size of text nodes.

Hinweis:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_PEDANTIC (int)
Sets XML_PARSE_PEDANTIC flag, which enables pedantic error reporting.

Hinweis:

Available as of PHP >= 5.4.0

LIBXML_XINCLUDE (int)
Implement XInclude substitution
LIBXML_ERR_ERROR (int)
A recoverable error
LIBXML_ERR_FATAL (int)
A fatal error
LIBXML_ERR_NONE (int)
No errors
LIBXML_ERR_WARNING (int)
A simple warning
LIBXML_VERSION (int)
libxml version like 20605 or 20617
LIBXML_DOTTED_VERSION (string)
libxml version like 2.6.5 or 2.6.17
LIBXML_SCHEMA_CREATE (int)
Create default/fixed value nodes during XSD schema validation

Hinweis:

Only available in Libxml >= 2.6.14 (as of 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)

Einführung

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Klassenbeschreibung

class LibXMLError {
/* Eigenschaften */
public int $level;
public int $code;
public int $column;
public string $message;
public string $file;
public int $line;
}

Eigenschaften

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.

Hinweis:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.

User Contributed Notes

There are no user contributed notes for this page.


libxml Funktionen

Inhaltsverzeichnis

  • libxml_clear_errors — Clear libxml error buffer
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Retrieve array of errors
  • libxml_get_external_entity_loader — Get the current external entity loader
  • libxml_get_last_error — Retrieve last error from libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Set the streams context for the next libxml document load or write
  • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


Clear libxml error buffer

  • « libxml Funktionen
  • libxml_disable_entity_loader »
  • PHP Manual
  • libxml Funktionen
  • Clear libxml error buffer

libxml_clear_errors

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

libxml_clear_errors — Clear libxml error buffer

Beschreibung

libxml_clear_errors(): void

libxml_clear_errors() clears the libxml error buffer.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Siehe auch

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml

User Contributed Notes

There are no user contributed notes for this page.


Disable the ability to load external entities

  • « libxml_clear_errors
  • libxml_get_errors »
  • PHP Manual
  • libxml Funktionen
  • 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

Warnung

Diese Funktion ist seit PHP 8.0.0 als DEPRECATED (veraltet) markiert. Von der Verwendung dieser Funktion wird dringend abgeraten.

Beschreibung

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.

Parameter-Liste

disable

Disable (true) or enable (false) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Rückgabewerte

Returns the previous value.

Siehe auch

  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • libxml_set_external_entity_loader() - Changes the default external entity loader
  • The LIBXML_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


Retrieve array of errors

  • « libxml_disable_entity_loader
  • libxml_get_external_entity_loader »
  • PHP Manual
  • libxml Funktionen
  • Retrieve array of errors

libxml_get_errors

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

libxml_get_errors — Retrieve array of errors

Beschreibung

libxml_get_errors(): array

Retrieve array of errors.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Beispiele

Beispiel #1 A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<titles>PHP: Behind the Parser</title>
</movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
$errors = libxml_get_errors();

foreach ($errors as $error) {
echo display_xml_error($error, $xml);
}

libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
$return = $xml[$error->line - 1] . "\n";
$return .= str_repeat('-', $error->column) . "^\n";

switch ($error->level) {
case LIBXML_ERR_WARNING:
$return .= "Warning $error->code: ";
break;
case LIBXML_ERR_ERROR:
$return .= "Error $error->code: ";
break;
case LIBXML_ERR_FATAL:
$return .= "Fatal Error $error->code: ";
break;
}

$return .= trim($error->message) .
"\n Line: $error->line" .
"\n Column: $error->column";

if ($error->file) {
$return .= "\n File: $error->file";
}

return "$return\n\n--------------------------------------------\n\n";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

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

Siehe auch

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

lech 29-Jul-2017 12:12
Please beware that the column property seems almost always to be invalid. I thought it only occurred when the line in question was long (and I was just about to submit a bug report with an example), however, at the time of posting, you can even see the problem in the example provided on this page: line 4 does not even have 46 characters. Where the XML line is long, the difference can be very large.

This property comes from the libxml extension, so in any case I don't think this is a PHP bug, however it is worth knowing that the value might be totally unreliable to save some confusion.

The PHP documentation page for the libXMLError class gives some indication, stating:

"This property isn't entirely implemented in libxml and therefore 0 is often returned."

(My libxml version: 2.9.1)


Get the current external entity loader

  • « libxml_get_errors
  • libxml_get_last_error »
  • PHP Manual
  • libxml Funktionen
  • 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

Beschreibung

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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.

Siehe auch

  • libxml_set_external_entity_loader() - Changes the default external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Retrieve last error from libxml

  • « libxml_get_external_entity_loader
  • libxml_set_external_entity_loader »
  • PHP Manual
  • libxml Funktionen
  • Retrieve last error from libxml

libxml_get_last_error

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

libxml_get_last_error — Retrieve last error from libxml

Beschreibung

libxml_get_last_error(): LibXMLError|false

Retrieve last error from libxml.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns a LibXMLError object if there is any error in the buffer, false otherwise.

Siehe auch

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

There are no user contributed notes for this page.


Changes the default external entity loader

  • « libxml_get_last_error
  • libxml_set_streams_context »
  • PHP Manual
  • libxml Funktionen
  • 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

Beschreibung

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

Parameter-Liste

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 Ressource, a String from which a resource can be opened. If null is returned, the entity reference resolution will fail.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

Siehe auch

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


Set the streams context for the next libxml document load or write

  • « libxml_set_external_entity_loader
  • libxml_use_internal_errors »
  • PHP Manual
  • libxml Funktionen
  • Set the streams context for the next libxml document load or write

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

Beschreibung

libxml_set_streams_context(resource $context): void

Sets the streams context for the next libxml document load or write.

Parameter-Liste

context

The stream context resource (created with stream_context_create())

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

Beispiel #1 A libxml_set_streams_context() example

<?php

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

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

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Siehe auch

  • stream_context_create() - Creates a stream context

User Contributed Notes

There are no user contributed notes for this page.


Disable libxml errors and allow user to fetch error information as needed

  • « libxml_set_streams_context
  • SimpleXML »
  • PHP Manual
  • libxml Funktionen
  • Disable libxml errors and allow user to fetch error information as needed

libxml_use_internal_errors

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

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

Beschreibung

libxml_use_internal_errors(?bool $use_errors = null): bool

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

Parameter-Liste

use_errors

Enable (true) user error handling or disable (false) user error handling. Disabling will also clear any existing libxml errors.

Rückgabewerte

This function returns the previous value of use_errors.

Changelog

Version | Beschreibung
8.0.0 | use_errors is nullable now. Previously, its default was false.

Beispiele

Beispiel #1 A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

// load the document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
foreach (libxml_get_errors() as $error) {
// handle errors here
}

libxml_clear_errors();
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(false)

Siehe auch

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors

User Contributed Notes

marcovtwout 07-May-2013 01:05
When using libxml_use_internal_errors(true), and perform a possibly memory intensive operation like simplexml_load_string() next, you might end up with a blank screen and no php error logged because the error message been suppressed.
james at dunmore dot me dot uk 21-Aug-2008 03:03
We use a custom error handler using  set_error_handler()  I found that after I call

libxml_use_internal_errors(false);

It resets my error_handler - not sure if this is a bug or not, I will report it as a bug - however, I needed to repeat my call to set_error_handler

(did confuse me for a while)
B Crawford 03-Oct-2007 06:22
When using this funtion, be sure to clear your internal error buffer. If you dn't and you are using this in a long running process, you may find that all your memory is used up.


SimpleXML

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Beispiele
    • Grundlegende Verwendung von SimpleXML
    • Behandlung von XML-Fehlern
  • SimpleXMLElement — Die Klasse SimpleXMLElement
    • SimpleXMLElement::addAttribute — Fügt einem SimpleXML-Element ein Attribut hinzu
    • SimpleXMLElement::addChild — Fügt dem XML-Knoten ein Kind-Element hinzu
    • SimpleXMLElement::asXML — Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert
    • SimpleXMLElement::attributes — Liefert die Attribute eines Elements
    • SimpleXMLElement::children — Findet Kindelemente des gegebenen Knotens
    • SimpleXMLElement::__construct — Erstellt ein neues SimpleXMLElement-Objekt
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::current — Returns the current element
    • SimpleXMLElement::getDocNamespaces — Liefert die im Dokument deklarierten Namensräume
    • SimpleXMLElement::getName — Ermittelt den Namen eines XML-Elements
    • SimpleXMLElement::getNamespaces — Gibt die im Dokument verwendeten Namespaces zurück
    • 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 — Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query
    • SimpleXMLElement::rewind — Rewind to the first element
    • SimpleXMLElement::saveXML — Alias von SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::valid — Check whether the current element is valid
    • SimpleXMLElement::xpath — Führt eine XPath-Anfrage auf XML-Daten aus
  • SimpleXMLIterator — Die Klasse SimpleXMLIterator
  • SimpleXML-Funktionen
    • simplexml_import_dom — Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten
    • simplexml_load_file — Übersetzt eine XML-Datei in ein Objekt
    • simplexml_load_string — Übersetzt einen XML-String in ein Objekt

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.


Einführung

Die SimpleXML-Extension bietet ein besonders einfaches und leicht zu handhabendes Toolset, um XML in ein Objekt zu konvertieren, das mit normalen Eigenschafts-Selektoren und Array-Iteratoren bearbeitet werden kann.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Diese Erweiterung ist standardmäßig aktiviert. Sie kann bei der Kompilierung mit der folgenden Option ausgeschaltet werden: --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


Beispiele

Inhaltsverzeichnis

  • Grundlegende Verwendung von SimpleXML
  • Behandlung von XML-Fehlern

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.


Grundlegende Verwendung von SimpleXML

Viele Beispiele in dieser Referenz benötigen einen XML-String. Anstatt diesen String in jedem Beispiel zu wiederholen, legen wir ihn in einer Datei ab, die wir in den Beispielen inkludieren. Diese eingebundene Datei zeigen wir Ihnen im folgenden Beispiel. Alternativ dazu können Sie ein XML-Dokument erstellen und es mit simplexml_load_file() einlesen.

Beispiel #1 Einzubindende Datei example.php mit 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;
?>

Die Einfachheit von SimpleXML ist besonders deutlich erkennbar, wenn man einen String oder eine Zahl aus einem XML-Dokument extrahieren will.

Beispiel #2 <plot> ermitteln

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

   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.

Um auf Elemente in einem XML-Dokument zuzugreifen, die Zeichen enthalten, die nicht dem PHP-Benennungsstandard entsprechen (z. B. der Bindestrich), können Sie den Elementnamen zwischen geschweifte Klammern und einfachen Anführungszeichen einschließen.

Beispiel #3 Auf <line> zugreifen

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

PHP solves all my web problems

Beispiel #4 Auf nicht-eindeutige Elemente per SimpleXML zugreifen

Existieren mehrere Instanzen eines Elements als Kinder eines einzigen Elternelements, lassen sich normale iterative Techniken einsetzen.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Für jeden <character>-Knoten geben wir ein separates <name> aus. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Hinweis:

Eigenschaften ($movies->movie im vorherigen Beispiel) sind keine Arrays. Sie sind iterierbare und zugreifbare Objekte.

Beispiel #5 Attribute verwenden

Bis jetzt haben wir nur das Auslesen von Elementnamen und ihrer Werte betrachtet. SimpleXML kann aber auch auf die Attribute eines Elements zugreifen. Der Zugriff auf die Attribute eines Elements funktioniert genauso, als würden Sie die Elemente eines Arrays ansprechen.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Zugriff auf die <rating>-Knoten des ersten Films
* Die Bewertungsskala wird zusätzlich ausgegeben. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Verwende Attribute als Element-Indizes
case 'thumbs':
echo $rating, ' Daumen hoch';
break;
case 'stars':
echo $rating, ' Sterne';
break;
}
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

7 Daumen hoch5 Sterne

Beispiel #6 Vergleichen von Elementen und Attributen mit Text

Um ein Element oder ein Attribut mit einem String zu vergleichen oder an eine Funktion zu übergeben, die einen String als Parameter benötigt, müssen Sie das Element respektive das Attribut in einen String casten. Verwenden Sie dafür (string), ansonsten behandelt PHP das Element als Objekt.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
print 'Mein Lieblingsfilm.';
}

echo htmlentities((string) $movies->movie->title);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

My favorite movie.PHP: Behind the Parser

Beispiel #7 Zwei Elemente vergleichen

Zwei SimpleXMLElements können auch dann als unterschiedlich betrachtet werden, wenn sie auf das gleiche Element zeigen.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(false)

Beispiel #8 XPath verwenden

SimpleXML verfügt über eine eingebaute XPath-Unterstützung. So finden Sie alle <character>-Elemente:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' gespielt von ', $character->actor, PHP_EOL;
}
?>

'//' wird hier als Wildcard verwendet. Um absolute Pfadangaben zu verwenden, lassen Sie einen der Schrägstriche weg.

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Ms. Coder gespielt von Onlivia Actora
Mr. Coder gespielt von El ActÓr

Beispiel #9 Werte setzen

Die Daten in SimpleXML müssen nicht konstant sein. Das Objekt erlaubt die Veränderung all seiner Elemente.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #10 Elemente und Attribute hinzufügen

SimpleXML verfügt über eine vereinfachte Möglichkeit, Kindelemente und Attribute hinzuzufügen.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #11 DOM-Interoperabilität

PHP hat einen Mechanismus, um XML-Knoten zwischen dem SimpleXML und dem DOM-Format zu konvertieren. Das Beispiel zeigt, wie man ein DOM-Element in SimpleXML verwandelt.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Fehler beim Parsen des Dokuments';
exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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.


Behandlung von XML-Fehlern

Die Behandlung von XML-Fehlern beim Laden von Dokumenten ist eine sehr einfache Sache. Durch die Verwendung der libxml-Funktionalität ist es möglich, alle XML-Fehlermeldungen beim Laden des Dokuments zu unterdrücken und danach über die aufgetretenen Meldungen zu iterieren.

Das libXMLError-Objekt, das von libxml_get_errors() zurückgegeben wird, hat verschiedene Eigenschaften. Dazu gehören message, line und column (Position) des jeweiligen Fehlers.

Beispiel #1 Laden eines defekten XML-Strings

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
echo "Laden des XML fehlgeschlagen\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Laden des XML fehlgeschlagen
    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

Siehe auch

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


Die Klasse SimpleXMLElement

(PHP 5, PHP 7, PHP 8)

Einführung

Stellt ein Element in einem XML-Dokument dar.

Klassenbeschreibung

class SimpleXMLElement implements Stringable, Countable, RecursiveIterator {
/* Methoden */
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

Version | Beschreibung
8.0.0 | SimpleXMLElement implementiert nun Stringable, Countable und RecursiveIterator.

Inhaltsverzeichnis

  • SimpleXMLElement::addAttribute — Fügt einem SimpleXML-Element ein Attribut hinzu
  • SimpleXMLElement::addChild — Fügt dem XML-Knoten ein Kind-Element hinzu
  • SimpleXMLElement::asXML — Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert
  • SimpleXMLElement::attributes — Liefert die Attribute eines Elements
  • SimpleXMLElement::children — Findet Kindelemente des gegebenen Knotens
  • SimpleXMLElement::__construct — Erstellt ein neues SimpleXMLElement-Objekt
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::current — Returns the current element
  • SimpleXMLElement::getDocNamespaces — Liefert die im Dokument deklarierten Namensräume
  • SimpleXMLElement::getName — Ermittelt den Namen eines XML-Elements
  • SimpleXMLElement::getNamespaces — Gibt die im Dokument verwendeten Namespaces zurück
  • 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 — Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query
  • SimpleXMLElement::rewind — Rewind to the first element
  • SimpleXMLElement::saveXML — Alias von SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::valid — Check whether the current element is valid
  • SimpleXMLElement::xpath — Führt eine XPath-Anfrage auf XML-Daten aus

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.


Fügt einem SimpleXML-Element ein Attribut hinzu

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Fügt einem SimpleXML-Element ein Attribut hinzu

SimpleXMLElement::addAttribute

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

SimpleXMLElement::addAttribute — Fügt einem SimpleXML-Element ein Attribut hinzu

Beschreibung

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Fügt einem SimpleXML-Element ein Attribut hinzu.

Parameter-Liste

qualifiedName

Der Name des hinzuzufügenden Attributs.

value

Der Wert des Attributs.

namespace

Wenn angegeben, der Namespace, zu dem das Attribut gehört.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

Hinweis:

Die aufgeführten Beispiele binden möglicherweise example.php ein, das die XML-Zeichenkette enthält, die im ersten Beispiel über die grundlegende Verwendung zu finden ist.

Beispiel #1 Hinzufügen von Attributen und Kindern zu einem SimpleXML-Element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: Noch mehr Parser-Geschichten');
$movie->addChild('plot', 'Alles ueber die Leute, die das Kind am Leben erhalten.');

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

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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

Siehe auch

  • SimpleXMLElement::addChild() - Fügt dem XML-Knoten ein Kind-Element hinzu
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

caffeinatedbits 09-Dec-2022 10:50
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo $animals->Dog->asXML();
// <Dog/>

?>
caffeinatedbits 09-Dec-2022 10:26
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
caffeinatedbits 09-Dec-2022 10:25
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
    foreach ($animals->Dog->attributes() as $attr => &$value) {
        if ("breed" === $attr) {
            $value = "poodle";
        }
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // An iterator cannot be used with foreach by reference
}

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
//     ["@attributes"]=>
//   array(1) {
//         ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


Fügt dem XML-Knoten ein Kind-Element hinzu

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Fügt dem XML-Knoten ein Kind-Element hinzu

SimpleXMLElement::addChild

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

SimpleXMLElement::addChild — Fügt dem XML-Knoten ein Kind-Element hinzu

Beschreibung

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Fügt ein Kind-Element an den Knoten und gibt ein SimpleXMLElement des Kindes zurück.

Parameter-Liste

qualifiedName

Der Name des hinzuzufügenden Kind-Elements.

value

Wenn angegeben, der Wert des Kind-Elements.

namespace

Wenn angegeben, der Namespace, zu dem das Kind-Element gehört.

Rückgabewerte

Die addChild-Methode gibt bei Erfolg ein SimpleXMLElement-Objekt zurück, das das zum XML-Knoten hinzugefügte Kind repräsentiert, oder false, falls ein Fehler auftrat.

Beispiele

Hinweis:

Die aufgeführten Beispiele binden möglicherweise example.php ein, das die XML-Zeichenkette enthält, die im ersten Beispiel über die grundlegende Verwendung zu finden ist.

Beispiel #1 Hinzufügen von Attributen und Kindern zu einem SimpleXML-Element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: Noch mehr Parser-Geschichten');
$movie->addChild('plot', 'Alles ueber die Leute, die das Kind am Leben erhalten.');

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

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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

Siehe auch

  • SimpleXMLElement::addAttribute() - Fügt einem SimpleXML-Element ein Attribut hinzu
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

fluxlicious at gmail dot com 23-Jan-2023 11:18
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
caffeinatedbits 09-Dec-2022 11:31
Just in case anyone else, like me, was trying to figure out a way to remove child elements...

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

unset($animals->Dog[2]);

echo $animals->asXML();

// <?xml version="1.0" encoding="utf-8"?>
// <Animals>
//         <Dog breed="chihuahua"/>
//         <Dog breed="poodle"/>
//
// </Animals>

?>

Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

$allowed_breeds = [
    'chihuahua',
    'poodle'
];

try {
    $index = 0;
    foreach ($animals->Dog as $dog) {
        if (!in_array($dog['breed'], $allowed_breeds)) {
            unset($animals->Dog[$index]);
        }
        $index++;
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // SimpleXMLElement is not properly initialized
}

?>
carlos dot eduardo dot debiasi at gmail dot com 22-Apr-2021 01:23
I create this function so you can through and array build the XML, this allows multiple keys with the same value.
The structure must follow

[
    'key' => 'nameOfTheKey',
    'attributes' => ['id' => '1'],
    'fields' => [
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '2'],
        ['key' => 'fieldWithChild', 'fields' => [
            ['key' => 'car', 'value' => '2'],
            ['key' => 'human', 'value' => '3'],
        ]],
    ]
];

Function:
 function toXml(\SimpleXMLElement $node, array $data)
    {
        foreach ($data as $key => $value) {
            $key = $value['key'];
            if (isset($value['value'])) {
                    $newNode = $node->addChild($key, $value['value']);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            } else {
                $newNode = $node->addChild($key);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            }
            if (isset($value['fields'])) {
                foreach ($value['fields'] as $keyField => $valueField) {
                    $this->toXml($newNode, [$keyField => $valueField]);
                }
            }
        }
    }
nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert

Beschreibung

public SimpleXMLElement::asXML(?string $filename = null): string|bool

Die asXML-Methode formatiert den Inhalt des Elternobjekts als XML Version 1.0.

Parameter-Liste

filename

Falls ein String-Wert angegeben wird, schreibt die Funktion die Daten in die Datei, anstatt sie direkt zurückzugeben.

Rückgabewerte

Ist der Parameter filename nicht angegeben, gibt die Funktion bei erfolgreicher Umwandlung einen String zurück oder false bei einem Fehler. Ist der Parameter angegeben, wird true zurückgegeben, wenn die Datei erfolgreich erstellt werden konnte; ansonsten ist der Rückgabewert false.

Changelog

Version | Beschreibung
8.0.0 | filename ist jetzt nullable (akzeptiert den NULL-Wert).

Beispiele

Beispiel #1 XML erstellen

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>zeugs</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML lässt sich ebenfalls auf Xpath-Ergebnisse anwenden:

Beispiel #2 Anwendung von asXML() auf SimpleXMLElement::xpath()-Ergebnisse

<?php
// Fortsetzung des obigen Beispiels

/* Suche nach <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo $node->asXML();
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<c>text</c><c>stuff</c>

Siehe auch

  • SimpleXMLElement::__toString() - Returns the string content
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr =
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>';

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ø, æ and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');


Liefert die Attribute eines Elements

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Liefert die Attribute eines Elements

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Liefert die Attribute eines Elements

Beschreibung

public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Die Funktion gibt die Attribute und Werte zurück, die innerhalb eines XML-Tags definiert wurden.

Hinweis: SimpleXML definiert für die meisten Methoden Regeln für das Hinzufügen von iterativen Eigenschaften. Diese können weder mit var_dump() oder auf andere Weise angezeigt werden.

Parameter-Liste

namespaceOrPrefix

Ein optionaler Namespace für das abgefragte Attribut

isPrefix

Standardmäßig auf false gesetzt

Rückgabewerte

Gibt ein SimpleXMLElement-Objekt zurück, das durchlaufen werden kann, um die Attribute des Elements zu erhalten.

Gibt null zurück, wenn der Aufruf auf einem SimpleXMLElement-Objekt erfolgt, das bereits ein Attribut anstatt eines Elements darstellt.

Beispiele

Beispiel #1 Einen XML-String auswerten

<?php
$string = <<<XML
<a>
<foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

name="one"
game="lonely"

Siehe auch

  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

jurchiks101 at gmail dot com 23-May-2018 12:38
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes
(but not both) without type-casting is to use the function `current()`:

<?php
$xml = new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
    'bar' => [
        $xml->bar,
        current($xml->bar),
    ],
    'baz' => [
        $xml->baz->attributes(),
        current($xml->baz->attributes()),
    ],
    'qux' => [
        // won't work here correctly
        $xml->qux,
        current($xml->qux),
        $xml->qux->attributes(),
        current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
andy dot locologic+101 at gmail dot com 14-Aug-2015 10:00
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

<?php
      $x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
      $attributes = iterator_to_array($x->attributes());
?>
zevnikrok 18-Dec-2014 11:01
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
webfelipemaia at gmail dot com 07-Sep-2013 05:11
Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condição definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)

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

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/?</link>
    </item>
</list>

Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.

<?php

$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {

        $role = $child->attributes();

        foreach($child as $key => $value) {

            if($role == "Language")
            echo("[".$key ."] ".$value . "<br />");

        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
adrian at foeder dot de 14-Jun-2013 10:15
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;
?>

This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.
totalwipeout at gmail dot com 08-Nov-2012 05:21
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $node is a SimpleXMLElement object

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after
$atts_array = $atts_array['@attributes'];

var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
                        //-             public '@attributes' => ...

var_dump($atts_array); //- outputs array (size=11) ...

?>
Hope this helps!
chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

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

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>


Findet Kindelemente des gegebenen Knotens

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Findet Kindelemente des gegebenen Knotens

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Findet Kindelemente des gegebenen Knotens

Beschreibung

public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Die Methode findet Kinder eines Elements. Das Ergebnis entspricht den normalen Iterierungsregeln.

Hinweis: SimpleXML definiert für die meisten Methoden Regeln für das Hinzufügen von iterativen Eigenschaften. Diese können weder mit var_dump() oder auf andere Weise angezeigt werden.

Parameter-Liste

namespaceOrPrefix

Ein XML-Namensraum.

isPrefix

Ist isPrefix true, dann wird namespaceOrPrefix als Prefix interpretiert. Ist es false, dann wird namespaceOrPrefix als Namensraum-URL interpretiert.

Rückgabewerte

Gibt ein SimpleXMLElement-Objekt zurück, unabhängig davon, ob der Knoten Kindknoten hat oder nicht, außer der Knoten stellt ein Attribut dar, denn in diesem Fall wird null zurückgegeben.

Beispiele

Beispiel #1 Ein children()-Pseudo-Array durchlaufen

<?php
$xml = new SimpleXMLElement(
'<person>
<child role="Sohn">
<child role="Tochter"/>
</child>
<child role="Tochter">
<child role="Sohn">
<child role="Sohn"/>
</child>
</child>
</person>');

foreach ($xml->children() as $second_gen) {
echo ' Die Person zeugte eine/n ' . $second_gen['role'];

foreach ($second_gen->children() as $third_gen) {
echo ', die/der eine/n ' . $third_gen['role'] . ' zeugte;';

foreach ($third_gen->children() as $fourth_gen) {
echo ' und diese/r ' . $third_gen['role'] .
' zeugte eine/n ' . $fourth_gen['role'];
}
}
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Die Person zeugte eine/n Sohn, die/der eine/n Tochter zeugte; Die Person zeugte
 eine/n Tochter, die/der eine/n Sohn zeugte; und diese/r Sohn zeugte eine/n Sohn

Beispiel #2 Arbeiten mit Namensräumen

<?php
$xml = '<example xmlns:foo="my.foo.urn">
<foo:a>Apfel</foo:a>
<foo:b>Banane</foo:b>
<c>Kirsche</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)

Siehe auch

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - Zählt alle Elemente eines Arrays oder eines Countable-Objekts

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/>';
}
?>


Erstellt ein neues SimpleXMLElement-Objekt

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Erstellt ein neues SimpleXMLElement-Objekt

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Erstellt ein neues SimpleXMLElement-Objekt

Beschreibung

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)

Erstellt ein neues SimpleXMLElement-Objekt.

Parameter-Liste

data

Ein wohlgeformter XML-String, oder der Pfad oder die URL zu einem XML-Dokument, wenn dataIsURL true ist.

options

Optional zu verwenden, um weitere Libxml-Parameter anzugeben, die das Lesen von XML-Dokumenten betreffen. Optionen, die die Ausgabe von XML-Dokumenten betreffen (z. B. LIBXML_NOEMPTYTAG) werden stillschweigend ignoriert.

Hinweis:

Es kann erforderlich sein, die Option LIBXML_PARSEHUGE zu übergeben, um tief verschachteltes XML oder sehr große Textknoten verarbeiten zu können.

dataIsURL

Standardmäßig ist dataIsURL false. Verwenden Sie true, um data als Pfad oder URL zu einem XML-Dokument an Stelle eines Daten-Strings anzugeben.

namespaceOrPrefix

Ein Namensraum-Präfix oder -URI.

isPrefix

true, wenn namespaceOrPrefix ein Präfix ist, false, wenn es ein URI ist; der Standardwert ist false.

Fehler/Exceptions

Erzeugt eine E_WARNING-Fehlermeldung für jeden gefundenen Fehler in den XML-Daten und wirft zusätzlich eine Exception, wenn die XML-Daten nicht geparst werden konnten.

Tipp

libxml_use_internal_errors() kann verwendet werden, um alle XML-Fehler zu unterdrücken, und libxml_get_errors(), um danach über diese zu iterieren.

Beispiele

Hinweis:

Die aufgeführten Beispiele binden möglicherweise example.php ein, das die XML-Zeichenkette enthält, die im ersten Beispiel über die grundlegende Verwendung zu finden ist.

Beispiel #1 Erstellen eines SimpleXMLElement-Objekts

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

PHP: Behind the Parser

Beispiel #2 Erstellen eines SimpleXMLElement-Objekts von einer URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', 0, true);
echo $sxe->asXML();

?>

Siehe auch

  • Grundlegende Verwendung von SimpleXML
  • simplexml_load_string() - Übersetzt einen XML-String in ein Objekt
  • simplexml_load_file() - Übersetzt eine XML-Datei in ein Objekt
  • Behandlung von XML-Fehlern
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • libxml_set_streams_context() - Set the streams context for the next libxml document load or write

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.


Counts the children of an element

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::current »
  • PHP Manual
  • SimpleXMLElement
  • Counts the children of an element

SimpleXMLElement::count

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

SimpleXMLElement::count — Counts the children of an element

Beschreibung

public SimpleXMLElement::count(): int

This method counts the number of children of an element.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the number of elements of an element.

Beispiele

Beispiel #1 Counting the number of children

<?php
$xml = <<<EOF
<people>
<person name="Person 1">
<child/>
<child/>
<child/>
</person>
<person name="Person 2">
<child/>
<child/>
<child/>
<child/>
<child/>
</person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Person 1 has got 3 children.
Person 2 has got 5 children.

Siehe auch

  • SimpleXMLElement::children() - Findet Kindelemente des gegebenen Knotens

User Contributed Notes

daniel dot erni at focusedpublishing dot com 22-Mar-2011 08:37
Alternative code for PHP < 5.3:
<?php
$count = $node->count(); // PHP > 5.3
$count = count($node->children()); // PHP < 5.3
?>


Returns the current element

  • « SimpleXMLElement::count
  • SimpleXMLElement::getDocNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Returns the current element

SimpleXMLElement::current

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

SimpleXMLElement::current — Returns the current element

Beschreibung

public SimpleXMLElement::current(): SimpleXMLElement
Warnung

Prior to PHP 8.0, SimpleXMLElement::current() was only declared on the subclass SimpleXMLIterator.

This method returns the current element as a SimpleXMLElement object.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the current element as a SimpleXMLElement object.

Fehler/Exceptions

Throws an Error on failure.

Changelog

Version | Beschreibung
8.1.0 | An Error is now thrown if SimpleXMLElement::current() is called on an invalid iterator. Previously, null was returned.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

Siehe auch

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


Liefert die im Dokument deklarierten Namensräume

  • « SimpleXMLElement::current
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Liefert die im Dokument deklarierten Namensräume

SimpleXMLElement::getDocNamespaces

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

SimpleXMLElement::getDocNamespaces — Liefert die im Dokument deklarierten Namensräume

Beschreibung

public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false

Gibt die im Dokument deklarierten Namensräume zurück.

Parameter-Liste

recursive

Sofern angegeben, werden alle Namensräume zurückgegeben, die in Eltern- und Kindknoten deklariert wurden. Andernfalls werden nur die im Wurzelknoten deklarierten Namensräume zurückgegeben.

fromRoot

Ermöglicht die rekursive Prüfung der Namensräume unter einem Kindknoten statt von der Wurzel des XML-Dokuments.

Rückgabewerte

Die getDocNamespaces-Methode gibt ein Array der Namensräume mit den ihnen zugeordneten URIs zurück.

Beispiele

Beispiel #1 Ermitteln der Dokument-Namensräume

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Beispiel #2 Arbeiten mit mehreren Namensräumen

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Siehe auch

  • SimpleXMLElement::getNamespaces() - Gibt die im Dokument verwendeten Namespaces zurück
  • SimpleXMLElement::registerXPathNamespace() - Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query

User Contributed Notes

There are no user contributed notes for this page.


Ermittelt den Namen eines XML-Elements

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Ermittelt den Namen eines XML-Elements

SimpleXMLElement::getName

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

SimpleXMLElement::getName — Ermittelt den Namen eines XML-Elements

Beschreibung

public SimpleXMLElement::getName(): string

Ermittelt den Namen eines XML-Elements.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Die getName-Methode gibt den Namen des durch das SimpleXMLElement-Objekt referenzierte XML-Tag als String zurück.

Beispiele

Hinweis:

Die aufgeführten Beispiele binden möglicherweise example.php ein, das die XML-Zeichenkette enthält, die im ersten Beispiel über die grundlegende Verwendung zu finden ist.

Beispiel #1 Ermitteln des XML-Element-Namens

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Gibt die im Dokument verwendeten Namespaces zurück

  • « SimpleXMLElement::getName
  • SimpleXMLElement::getChildren »
  • PHP Manual
  • SimpleXMLElement
  • Gibt die im Dokument verwendeten Namespaces zurück

SimpleXMLElement::getNamespaces

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

SimpleXMLElement::getNamespaces — Gibt die im Dokument verwendeten Namespaces zurück

Beschreibung

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

Gibt die im Dokument verwendeten Namespaces zurück

Parameter-Liste

recursive

Sofern angegeben, werden alle Namespaces, die in Eltern- und Kindknoten verwendet werden, zurückgegeben. Ansonsten werden nur die Namespaces des Wurzelknoten zurückgegeben.

Rückgabewerte

Die getNamespaces-Methode gibt ein Array der Namespaces mit ihren zugehörigen URIs zurück.

Beispiele

Beispiel #1 Verwendete Dokument-Namespaces zurückgeben

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Siehe auch

  • SimpleXMLElement::getDocNamespaces() - Liefert die im Dokument deklarierten Namensräume
  • SimpleXMLElement::registerXPathNamespace() - Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query

User Contributed Notes

thiago at osfeio dot com 29-Oct-2013 04:23
this article has more info : http://www.sitepoint.com/parsing-xml-with-simplexml/
harry at nospam dot thestorm dot plus dot com 17-Feb-2012 02:21
If the namespace is nested in the xml, then you will have to loop over the nodes.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
  <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
      <items>
            <title>This is a test of namespaces and my patience</title>
            <p:person id="1">John Doe</p:person>
            <p:person id="2">Susie Q. Public</p:person>
            <p:person id="1">Fish Man</p:person>
      </items>
  </people>
XML;

$sxe = new SimpleXMLElement($xml);

foreach ($sxe as $out_ns)
{
    $ns = $out_ns->getNamespaces(true);

    $child = $out_ns->children($ns['p']);

    foreach ($child as $out)
    {
        echo $out . "<br />";
    }
}
?>
harry at nospam dot thestorm dot plus dot com 16-Feb-2012 12:50
To read a namespace node you have to use the children method.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach ($child->person as $out_ns)
{
    echo $out_ns;
}

?>


Returns the sub-elements of the current element

  • « SimpleXMLElement::getNamespaces
  • SimpleXMLElement::hasChildren »
  • PHP Manual
  • SimpleXMLElement
  • Returns the sub-elements of the current element

SimpleXMLElement::getChildren

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

SimpleXMLElement::getChildren — Returns the sub-elements of the current element

Beschreibung

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Warnung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns a SimpleXMLElement object containing the sub-elements of the current element.

Beispiele

Beispiel #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";
}
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

The title is 'PHP Basics' from the class SimpleXMLElement
The author is 'Jim Smith' from the class SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the current element has sub elements

  • « SimpleXMLElement::getChildren
  • SimpleXMLElement::key »
  • PHP Manual
  • SimpleXMLElement
  • Checks whether the current element has sub elements

SimpleXMLElement::hasChildren

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

SimpleXMLElement::hasChildren — Checks whether the current element has sub elements

Beschreibung

public SimpleXMLElement::hasChildren(): bool
Warnung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

true if the current element has sub-elements, otherwise false

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(SimpleXMLElement)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

There are no user contributed notes for this page.


Return current key

  • « SimpleXMLElement::hasChildren
  • SimpleXMLElement::next »
  • PHP Manual
  • SimpleXMLElement
  • Return current key

SimpleXMLElement::key

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

SimpleXMLElement::key — Return current key

Beschreibung

public SimpleXMLElement::key(): string
Warnung

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.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

Fehler/Exceptions

Throws an Error on failure.

Changelog

Version | Beschreibung
8.1.0 | An Error is now thrown if SimpleXMLElement::key() is called on an invalid iterator. Previously, false was returned.

Beispiele

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(false)
string(4) "book"

User Contributed Notes

There are no user contributed notes for this page.


Move to next element

  • « SimpleXMLElement::key
  • SimpleXMLElement::registerXPathNamespace »
  • PHP Manual
  • SimpleXMLElement
  • Move to next element

SimpleXMLElement::next

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

SimpleXMLElement::next — Move to next element

Beschreibung

public SimpleXMLElement::next(): void
Warnung

Prior to PHP 8.0, SimpleXMLElement::next() was only declared on the subclass SimpleXMLIterator.

This method moves the SimpleXMLElement to the next element.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query

  • « SimpleXMLElement::next
  • SimpleXMLElement::rewind »
  • PHP Manual
  • SimpleXMLElement
  • Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query

SimpleXMLElement::registerXPathNamespace

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

SimpleXMLElement::registerXPathNamespace — Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query

Beschreibung

public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool

Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query. Dies ist besonders hilfreich, wenn der Anbieter des übergebenen XML-Dokuments die Namespace-Prefixe verändert hat. registerXPathNamespace erzeugt einen Prefix für die dazugehörigen Namespaces, die das Abfragen der Knoten in diesem Namespace erlauben, ohne dass der Code verändert werden muss, um die vom Anbieter diktierten neuen Prefixes zu erlauben.

Parameter-Liste

prefix

Der Namespace-Prefix der im XPath-Query für den angegebenen Namespace verwendet werden soll. namespace.

namespace

Der Namespace, der für den XPath-Query verwendet wird. Dies muss einem Namespace entsprechen, der im XML-Dokument oder im XPath-Query verwendet wird.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

Beispiel #1 Einen Namespace-Prefix zur Verwendung in einem XPath-Query setzen

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

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Chapter 1
Chapter 2

Beachten Sie wie das im Beispiel vorgestellte XML-Dokument die Namespaces mit dem Prefix chap verwendet. Stellen Sie sich vor, dass dieses Dokument (oder ein anderes dieser Art) in der Vergangenheit den Prefix c für den selben Namespace verwendete. Seit dieser Änderung gibt der XPath-Query keine gültigen Resultate mehr zurück und der Query benötigt eine Überarbeitung. Die Verwendung von registerXPathNamespace bewahrt Sie vor zukünftigen Modifikationen des Querys, auch wenn der Anbieter die Namespace-Prefixes verändert.

Siehe auch

  • SimpleXMLElement::xpath() - Führt eine XPath-Anfrage auf XML-Daten aus
  • SimpleXMLElement::getDocNamespaces() - Liefert die im Dokument deklarierten Namensräume
  • SimpleXMLElement::getNamespaces() - Gibt die im Dokument verwendeten Namespaces zurück

User Contributed Notes

Lea Hayes 12-Jan-2011 09:56
Looks like you have to use registerXPathNamespace for each node when using XPath:

<?php
$xml = simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// Breaks with out the following line:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>


Rewind to the first element

  • « SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::saveXML »
  • PHP Manual
  • SimpleXMLElement
  • Rewind to the first element

SimpleXMLElement::rewind

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

SimpleXMLElement::rewind — Rewind to the first element

Beschreibung

public SimpleXMLElement::rewind(): void
Warnung

Prior to PHP 8.0, SimpleXMLElement::rewind() was only declared on the subclass SimpleXMLIterator.

This method rewinds the SimpleXMLElement to the first element.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Alias von SimpleXMLElement::asXML

  • « SimpleXMLElement::rewind
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Alias von SimpleXMLElement::asXML

SimpleXMLElement::saveXML

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

SimpleXMLElement::saveXML — Alias von SimpleXMLElement::asXML()

Beschreibung

Diese Methode ist ein Alias für: SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Returns the string content

  • « SimpleXMLElement::saveXML
  • SimpleXMLElement::valid »
  • PHP Manual
  • SimpleXMLElement
  • Returns the string content

SimpleXMLElement::__toString

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

SimpleXMLElement::__toString — Returns the string content

Beschreibung

public SimpleXMLElement::__toString(): string

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns the string content on success or an empty string on failure.

Beispiele

Beispiel #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1 3

Siehe auch

  • SimpleXMLElement::asXML() - Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert

User Contributed Notes

mmj at example dot net 02-Oct-2017 03:22
__toString() is not intended to be called directly.

Instead, it defines what is returned when the object is cast to string, either explicitly with:

(string)$element

Or implicitly, when used in certain contexts which would cause a conversion to string.
Patanjali 27-Mar-2016 10:55
[Someone remove that other Patanjali's note, because it has errors! :-(]

For those for whom it may not be immediately obvious from the example, the echo is what is forcing __toString() to be used.

However, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

$Text = $XML->__toString();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span->__toString();
$Text = $XML->span[0]->__toString();

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1]->__toString();

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.
Patanjali 27-Mar-2016 10:36
For those for whom it may not be immediately obvious from the example, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

Either:
$Text = $XML;
$Text = $XML->__String();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span;
$Text = $XML->span[0];

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1];

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.


Check whether the current element is valid

  • « SimpleXMLElement::__toString
  • SimpleXMLElement::xpath »
  • PHP Manual
  • SimpleXMLElement
  • Check whether the current element is valid

SimpleXMLElement::valid

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

SimpleXMLElement::valid — Check whether the current element is valid

Beschreibung

public SimpleXMLElement::valid(): bool
Warnung

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

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns true if the current element is valid, otherwise false

Beispiele

Beispiel #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.


Führt eine XPath-Anfrage auf XML-Daten aus

  • « SimpleXMLElement::valid
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Führt eine XPath-Anfrage auf XML-Daten aus

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Führt eine XPath-Anfrage auf XML-Daten aus

Beschreibung

public SimpleXMLElement::xpath(string $expression): array|null|false

Die xpath-Methode durchsucht den SimpleXML-Knoten nach Kind-Elementen, die der XPath expression-Anfrage entsprechen.

Parameter-Liste

expression

Ein XPath-Pfad.

Rückgabewerte

Die Funktion gibt bei Erfolg ein Array von SimpleXMLElement-Objekten zurück und null oder false im Fehlerfall.

Beispiele

Beispiel #1 Xpath

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>zeugs</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Suche nach <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}

/* Relative Pfade funktionieren ebenfalls ... */
$result = $xml->xpath('b/c');

foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

/a/b/c: text
/a/b/c: zeugs
b/c: text
b/c: zeugs

Beachten Sie, dass beide Ergebnisse gleich sind.

Siehe auch

  • SimpleXMLElement::registerXPathNamespace() - Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query
  • SimpleXMLElement::getDocNamespaces() - Liefert die im Dokument deklarierten Namensräume
  • SimpleXMLElement::getNamespaces() - Gibt die im Dokument verwendeten Namespaces zurück
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

Filippo Vicari 28-Sep-2022 09:56
You can also search for siblings with a condition. For example immagine to need the title for a desidered language which with the two siblings tags in this XML file

<?xml version="1.0" encoding="UTF-8"?>
<IDOC BEGIN="1">
...
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>E</LANG>
    <TITLE>Name</TITLE>
    <LANG_ISO>EN</LANG_ISO>
</PRODUCT>
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>I</LANG>
    <TITLE>Name I</TITLE>
    <LANG_ISO>IT</LANG_ISO>
</PRODUCT>
...
</IDOC>

Let's break it down
<?php
"//PRODUCT" // find product tag
"//PRODUCT/LANG[.='E']" // whithin it find lang == "E"
"//PRODUCT/LANG[.='E']/../"  // go up one step
"//PRODUCT/LANG[.='E']/../TITLE" // get the title Tag content

// Combined search and find siblings ----------------------------
$xml = simplexml_load_file("fname.xml");

// Search for the TITLE field which sibling is == "E" ----------
$title_E_array = $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE"); // By default gives back an array of  SimpleXmlElement
$title = (string) $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE")[0]; // in this way saves only the value as a string
?>
awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


Die Klasse SimpleXMLIterator

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

Einführung

Der SimpleXMLIterator ermöglicht die rekursive Iteration über alle Knoten eines SimpleXMLElement-Objektes.

Klassenbeschreibung

class SimpleXMLIterator extends SimpleXMLElement {
/* Geerbte Methoden */
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

Version | Beschreibung
8.0.0 | Die Iteratormethoden (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(), SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) wurden zu SimpleXMLElement verschoben.
8.0.0 | SimpleXMLIterator implementiert nun Stringable.

User Contributed Notes

prouchetvincent at free dot fr 10-Oct-2020 12:47
<?php
=======================================================
$index =
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <article id="8" visibility="true" filename="2020-10-08" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="7" visibility="true" filename="2020-10-07" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="6" visibility="true" filename="2020-10-02" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="5" visibility="true" filename="2020-09-30" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="4" visibility="true" filename="2020-09-26" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="3" visibility="true" filename="2020-09-22"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="2" visibility="true" filename="2020-09-20"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
        <article id="1" visibility="true" filename="hello world" fileExtension="xml">
            Hello World
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
</root>
====================================================================
?>
If you have to use an iterator to parse your XML
and need tu get an attribute of tags of this iterator then
use the fonction
->current()
of simpleXMLIterator on your object before
->attributes()->{attibute name}
<?php
$file="";
try{
     $index = new SimpleXMLIterator ( file_get_contents ( FILEDIRECTORY. 'index.xml' ) );}
catch(Exception $e) {whatever you want to do on error}}

for( $index->rewind(); $index->valid(); $index->next() ) {
    try {
          $file = file_get_contents(FILESDIRECTORY.$index->current()->attributes()->{'fileName'}. '.xml' );
    } catch (Exception $e) {whatever you want to do on error}
    $article = new Article ();
    $article->setXMLArticle ($file);
    array_push( $this->articles, $article );
    $file ="";
    }
}
?>
This exemple use a custom made Article object that itself parse the file given to him to initialise its properties .
Here we open a file (Yes I use constant for my directories)
make it a simpleXMLIterator and parse article elements to get the filename attribute to use it to open another XML file for data collection.
don't forget !!! In PHP Object created by new ClassName() are ALWAYS given by reference that is why new Article() in inside the loop and not outside
(yhea, I did that mistake)
XMLIterator are powerfull yet harder to understand in themselves but once passed that one point.
They are very more easier to use than plain arrays.
rukkykf at gmail dot com 16-Dec-2018 06:54
I think it's worth mentioning that you need to call the rewind() method on the SimpleXMLIterator object immediately after initialization before you can start doing any other operations on the object. An example:

<?php
$xml = new SimpleXMLIterator('file.xml', null, true);

// $x here will be set to null because the rewind() method has not been called
$x = $xml->current();

$xml->rewind();

// $x here will be set to the first element
$x = $xml->current();

?>
php-lover at live dot com 05-Oct-2015 09:50
Function to extract SimpleXMLElement data to array.

function extract($sxe = null) {
    if (!$sxe instanceOf SimpleXMLElement)
        return array();

    $extract = array();

    foreach ($sxe->children() as $key => $value) {
        if (array_key_exists($key, $extract)) {
            if (!isset($extract[$key][0])) {
                $tmp_extract = $extract[$key];
                $extract[$key] = array();
                $extract[$key][0] = $tmp_extract;
            } else
                $extract[$key] = (array) $extract[$key];
        }

        if ($value->count()) {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = $this->extract($value);
            else
                $extract[$key] = $this->extract($value);
        } else {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = empty(strval($value)) ? null : strval($value);
            else
                $extract[$key] = empty(strval($value)) ? null : strval($value);
        }
    }

    return $extract;
}
centy2010 at hotmail dot com 16-Jul-2014 03:22
I filled my database from an XML file about 1260 Kb.
I made my process less than a second. Simply by using SimpleXML.

I give you a little example of the usage to fill a database.
Given the table universe.
With 4 columns Coords, Planet_Name, Player_id, Moon_Size.

Now You have a XML file named universe.xml with this kind of data.
I enclose the data within php tags but it's a file :p
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<universe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -
xsi:noNamespaceSchemaLocation="http://s127-fr.ogame.gameforge.com/api/xsd/universe.xsd" -
timestamp="1405413350" serverId="fr127">
    <planet id="1" player="1" name="Arakis" coords="1:1:2">
        <moon id="2" name="Mond" size="4998"/>
    </planet>
    <planet id="33620176" player="100000" name="GameAdmin" coords="1:1:3"/>
    <planet id="33620179" player="100003" name="Heimatplanet" coords="1:1:1"/>
    <planet id="33620186" player="100004" name="OGame Team" coords="6:250:1"/>
    <planet id="33620242" player="100058" name="KnS" coords="9:1:6">
        <moon id="33668391" name="Lune" size="8831"/>
    </planet>
</universe>
EOT;
?>

Now how to bring these data in my 4 columns table :

<?php
$newfname = $path."Universe.XML";
$mydata = new SimpleXmlIterator($newfname, 0, true);
$myquery = "INSERT INTO `".$tablename."` (`coords`,`planet_name`, `player_id`, `moon_size`) VALUES ";
for ($mydata->rewind();$mydata->valid();$mydata->next()) {
    $myquery.= " ('".$mydata->current()->attributes()['coords']
_."','".utf8_decode($mydata->current()->attributes()['name'])
_."','".utf8_decode($mydata->current()->attributes()['player'])
_."','";
    if ($mydata->haschildren()) {
        $myquery.= $mydate->current()->children()->attributes()['size']."'),";
    } else {
        $myquery.= "'),";
    }
}
$myquery = rtrim($myquery, ",");
$datatosql = mysql_query($myquery);
?>
hezll at msn dot com 11-Apr-2013 04:34
Most of the time we need to convert the XML to array or JSON , but now I have to completed the requirement of converting XML to XPath which make our template easily geting the data from XML data source due to the Xpath mapping .Here is the function:

<?php

function sxiToXpath($sxi, $key = null, &$tmp = null)
{
    $keys_arr = array();
    //get the keys count array
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (array_key_exists($sk, $keys_arr))
        {
            $keys_arr[$sk]+=1;
            $keys_arr[$sk] = $keys_arr[$sk];
        }
        else
        {
            $keys_arr[$sk] = 1;
        }
    }
    //create the xpath
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (!isset($$sk))
        {
            $$sk = 1;
        }
        if ($keys_arr[$sk] >= 1)
        {
            $spk = $sk . '[' . $$sk . ']';
            $keys_arr[$sk] = $keys_arr[$sk] - 1;
            $$sk++;
        }
        else
        {
            $spk = $sk;
        }
        $kp = $key ? $key . '/' . $spk : '/' . $sxi->getName() . '/' . $spk;
        if ($sxi->hasChildren())
        {
            sxiToXpath($sxi->getChildren(), $kp, $tmp);
        }
        else
        {
            $tmp[$kp] = strval($sxi->current());
        }
        $at = $sxi->current()->attributes();
        if ($at)
        {
            $tmp_kp = $kp;
            foreach ($at as $k => $v)
            {
                $kp .= '/@' . $k;
                $tmp[$kp] = $v;
                $kp = $tmp_kp;
            }
        }
    }
    return $tmp;
}

function xmlToXpath($xml)
{
    $sxi = new SimpleXmlIterator($xml);
    return sxiToXpath($sxi);
}

/**
 *  How to use the function
 */
$xml = <<<EOT
<?xml version="1.0" encoding="utf8" ?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002" IDd="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company id='id_test'><g id='id_g'>glove</g></Company>
   </item>
    <item>
    </item>
</data>
EOT;

$rs = xmlToXpath($xml);
print_r($rs);

/**
 * the results may lkie this:
Array
(
    [/data/item[1]/Company[1]] => Navarro Corp.
    [/data/item[1]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30001
        )
    [/data/item[2]/Company[1]] => Performant Systems
    [/data/item[2]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[2]/@IDd] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[3]/Company[1]/g[1]] => glove
    [/data/item[3]/Company[1]/g[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_g
        )

    [/data/item[3]/Company[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_test
        )

    [/data/item[3]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30003
        )

    [/data/item[4]] =>

)
 */

echo "Total:" . count($rs);

echo "<hr>";
/* You can check the xpath result like this */
$xml = new SimpleXMLElement($xml);
foreach ($rs as $k => $v)
{
    echo "Xpath:" . $k . " |Value:" . $v . " ";
    var_dump($xml->xpath($k));
    echo "<br>";
}
ajnsit dot NOSPAM at gmail dot com 17-Mar-2011 10:14
Here's a simple function to convert an XML string to an array -

<?php
// PHP5.3 and above only
function parse($str) {
    $f = function($iter) {
      foreach($iter as $key=>$val)
        $arr[$key][] = ($iter->hasChildren())?
          call_user_func (__FUNCTION__, $val)
          : strval($val);
      return $arr;
    };
    return $f(new SimpleXmlIterator($str, null));
}
?>

PHP 5.2 and below do not have anonymous functions.
But you can create a helper function to achieve the same thing -

<?php
  function parse($str) {
    return parseHelper(new SimpleXmlIterator($str, null));
  }
  function parseHelper($iter) {
    foreach($iter as $key=>$val)
      $arr[$key][] = ($iter->hasChildren())?
        call_user_func (__FUNCTION__, $val)
        : strval($val);
    return $arr;
  }
?>

Using it is straightforward enough -

<?php

$xml = '
<movies>
  <movie>abcd</movie>
  <movie>efgh</movie>
  <movie>hijk</movie>
</movies>';
var_dump(parse($xml));

?>

This will output -

array
  'movie' =>
    array
      0 => string 'abcd' (length=4)
      1 => string 'efgh' (length=4)
      2 => string 'hijk' (length=4)
ratfactor at gmail dot com 19-Jul-2009 05:08
The documentation is a bit sparse for SimpleXmlIterator.  Here is an example showing the use of its methods. xml2Array and sxiToArray work together to convert an XML document to an associative array structure.

The contents of cats.xml:
======================================
<cats>
  <cat>
      <name>Jack</name>
      <age>2</age>
      <color>grey</color>
      <color>white</color>
  </cat>
  <cat>
      <name>Maxwell</name>
      <age>12</age>
      <color>orange</color>
      <color>black</color>
  </cat>
</cats>
======================================

<?php
function xml2array($fname){
  $sxi = new SimpleXmlIterator($fname, null, true);
  return sxiToArray($sxi);
}

function sxiToArray($sxi){
  $a = array();
  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
    if(!array_key_exists($sxi->key(), $a)){
      $a[$sxi->key()] = array();
    }
    if($sxi->hasChildren()){
      $a[$sxi->key()][] = sxiToArray($sxi->current());
    }
    else{
      $a[$sxi->key()][] = strval($sxi->current());
    }
  }
  return $a;
}

// Read cats.xml and print the results:
$catArray = xml2array('cats.xml');
print_r($catArray);
?>

Results (reformatted a bit for compactness and clarity):
======================================
Array(
  [cat] => Array(
    [0] => Array(
      [name] => Array(  [0] => Jack    )
      [age] => Array(   [0] => 2       )
      [color] => Array( [0] => grey,
                        [1] => white   )
    )
    [1] => Array(
      [name] => Array(  [0] => Maxwell )
      [age] => Array(   [0] => 12      )
      [color] => Array( [0] => orange
                        [1] => black   )
    )
  )
)


SimpleXML-Funktionen

Inhaltsverzeichnis

  • simplexml_import_dom — Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten
  • simplexml_load_file — Übersetzt eine XML-Datei in ein Objekt
  • simplexml_load_string — Übersetzt einen XML-String in ein Objekt

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.


Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten

  • « SimpleXML-Funktionen
  • simplexml_load_file »
  • PHP Manual
  • SimpleXML-Funktionen
  • Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten

Beschreibung

simplexml_import_dom(object $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement

Die Funktion wandelt einen Knoten eines DOM-Dokuments in einen SimpleXML-Knoten um. Das neue Objekt kann wie ein normales SimpleXML-Element verwendet werden.

Parameter-Liste

node

Ein DOM-Element-Knoten.

class_name

Der optionale Parameter kann verwendet werden, wenn simplexml_import_dom() ein Objekt der spezifischen Klasse zurückgeben soll. Die gewählte Klasse sollte von der Klasse SimpleXMLElement abgeleitet sein.

Rückgabewerte

Gibt ein SimpleXMLElement-Objekt zurück oder null, falls ein Fehler auftrat.

Beispiele

Beispiel #1 DOM-Import

<?php
$dom = new DOMDocument;
$dom->loadXML('<buecher><buch><titel>blah</titel></buch></buecher>');
if (!$dom) {
echo 'Fehler beim Parsen des Dokuments';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->buch[0]->titel;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

blah

Siehe auch

  • dom_import_simplexml() - Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

paul dot allsopp at digital-pig dot com 06-Jun-2023 12:07
Why not just:
simplexml_import_dom(dom_import_simplexml($SimpleXmlNode))
shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


Übersetzt eine XML-Datei in ein Objekt

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • SimpleXML-Funktionen
  • Übersetzt eine XML-Datei in ein Objekt

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Übersetzt eine XML-Datei in ein Objekt

Beschreibung

simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Die Funktion wandelt das übergebene wohlgeformte (well-formed) XML-Dokument in ein Objekt um.

Parameter-Liste

filename

Der Pfad zur XML-Datei.

class_name

Der optionale Parameter class_name kann verwendet werden, wenn simplexml_load_file() ein Objekt der spezifischen Klasse zurückgeben soll. Die gewählte Klasse sollte von der Klasse SimpleXMLElement abgeleitet sein.

options

Bitweises OR von libxml-Konstanten für weitere Optionen.

namespace_or_prefix

Ein Namensraum-Präfix oder URI.

is_prefix

true, wenn namespace_or_prefix ein Präfix ist, false, wenn er ein URI ist. Der Standardwert ist false.

Rückgabewerte

Gibt ein Objekt der Klasse SimpleXMLElement zurück, dessen Eigenschaften die Daten des XML-Dokuments enthalten. Bei einem Fehler wird false zurückgegeben.

Warnung

Diese Funktion kann sowohl das boolsche false zurückliefern, als auch einen nicht-boolschen Wert, welcher zu false ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Fehler/Exceptions

Generiert eine Fehlermeldung vom Typ E_WARNING für jeden in den XML-Daten gefundenen Fehler.

Tipp

libxml_use_internal_errors() kann hier verwendet werden, um alle XML-Fehlermeldungen auszublenden, und libxml_get_errors(), um danach darüber zu iterieren.

Beispiele

Beispiel #1 Ein XML-Dokument auswerten

<?php
// Die Datei test.xml enthält ein XML-Dokument mit einem Wurzel-Element
// und mindestens einem Element /[root]/title.

if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');

print_r($xml);
} else {
exit('Konnte test.xml nicht öffnen.');
}
?>

Das Skript gibt nach erfolgreichem Laden folgendes aus:

SimpleXMLElement Object
(
  [title] => Beispiel-Titel
  ...
)

Ab diesem Punkt können $xml->title und andere Elemente verwendet werden.

Siehe auch

  • simplexml_load_string() - Übersetzt einen XML-String in ein Objekt
  • SimpleXMLElement::__construct() - Erstellt ein neues SimpleXMLElement-Objekt
  • Behandlung von XML-Fehlern
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Grundlegende Verwendung von SimpleXML
  • libxml_set_streams_context() - Set the streams context for the next libxml document load or write

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


Übersetzt einen XML-String in ein Objekt

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • SimpleXML-Funktionen
  • Übersetzt einen XML-String in ein Objekt

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Übersetzt einen XML-String in ein Objekt

Beschreibung

simplexml_load_string(
string $data,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Die Funktion erwartet einen wohlgeformten (well-formed) XML-String und gibt ihn als Objekt zurück.

Parameter-Liste

data

Ein wohlgeformter XML-String.

class_name

Der optionale Parameter class_name kann verwendet werden, wenn simplexml_load_string() ein Objekt der spezifischen Klasse zurückgeben soll. Die gewählte Klasse sollte von der Klasse SimpleXMLElement abgeleitet sein.

options

Bitweises OR von libxml-Konstanten für weitere Optionen.

namespace_or_prefix

Namensraum-Präfix oder URI.

is_prefix

true, wenn namespace_or_prefix ein Präfix ist, false, wenn er ein URI ist. Standardwert ist false.

Rückgabewerte

Gibt ein Objekt der Klasse SimpleXMLElement zurück, dessen Eigenschaften die Daten beinhalten, wie sie im XML-Dokument abgebildet sind. Tritt ein Fehler auf, wird false zurückgegeben.

Warnung

Diese Funktion kann sowohl das boolsche false zurückliefern, als auch einen nicht-boolschen Wert, welcher zu false ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Fehler/Exceptions

Generiert eine Fehlermeldung vom Typ E_WARNING für jeden in den XML-Daten gefundenen Fehler.

Tipp

libxml_use_internal_errors() kann hier verwendet werden, um alle XML-Fehlermeldungen auszublenden, und libxml_get_errors(), um danach darüber zu iterieren.

Beispiele

Beispiel #1 Einen XML-String auswerten

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Zweiundvierz...?</title>
<from>Joe</from>
<to>Jane</to>
<body>
Ich kenne die Antwort -- aber was ist die Frage?
</body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

SimpleXMLElement Object
(
  [title] => Zweiundvierz...?
  [from] => Joe
  [to] => Jane
  [body] =>
   Ich kenne die Antwort -- aber was ist die Frage?
)

Ab diesem Punkt können Sie $xml->body etc. verwenden.

Siehe auch

  • simplexml_load_file() - Übersetzt eine XML-Datei in ein Objekt
  • SimpleXMLElement::__construct() - Erstellt ein neues SimpleXMLElement-Objekt
  • Behandlung von XML-Fehlern
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Grundlegende Verwendung von SimpleXML

User Contributed Notes

erguven dot m at gmail dot com 11-May-2017 03:14
if you want to use a class which exists in a name space, use it full name. simple_load_string did not recognize short one.

class.new.php
<?php
namespace foo\bar;

class new extends SimpleXMLElement
{
    public function do()
    {
        echo "done";
    }
}
?>

false.php
<?php
use \foo\bar\new;

$result = simplexml_load_string($xml, 'new'); // it gives warning
$result->do(); // fatal error
?>

true.php
<?php
use \foo\bar\new;
$result = simplexml_load_string($xml, '\foo\bar\new');

$result->do(); // prints done
?>
artistan at gmail dot com 11-Jun-2015 12:32
Here is my update to Bob's simple SimpleXML wrapper function.
I noticed his version would turn an empty SimpleXMLElement into an empty array.

<?php
    /**
     * http://php.net/manual/en/function.simplexml-load-string.php#91564
     *
     * bool/array unserialize_xml ( string $input [ , callback $callback ] )
     * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
     * Returns false on all failure
     * Notes:
     * Root XML tags are stripped
     * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
     * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
     *
     * @param $input
     * @param null $callback
     * @param bool $recurse
     * @return array|mixed
     *
     */
    function unserialize_xml($input, $callback = null, $recurse = false)
    {
        // Get input, loading an xml string with simplexml if its the top level of recursion
        $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
        // Convert SimpleXMLElements to array
        if ($data instanceof SimpleXMLElement){
            if(!empty($data)){
                $data = (array) $data;
            } else {
                $data = '';
            }
        }
        // Recurse into arrays
        if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
        // Run callback and return
        return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
    }
?>
meustrus 07-May-2015 03:38
Be careful checking for parse errors. An empty SimpleXMLElement may resolve to FALSE, and if your XML contains no text or only contains namespaced elements your error check may be wrong. Always use `=== FALSE` when checking for parse errors.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Root xmlns:ns1="http://example.com/custom">
<ns1:Node>There's stuff here</ns1:Node>
</ns1:Root>
XML;

$simplexml = simplexml_load_string($xml);

// This prints "Parse Error".
echo ($simplexml ? 'Valid XML' : 'Parse Error'), PHP_EOL;

// But this prints "There's stuff here", proving that
// the SimpleXML object was created successfully.
echo $simplexml->children('http://example.com/custom')->Node, PHP_EOL;

// Use this instead:
echo ($simplexml !== FALSE ? 'Valid XML' : 'Parse Error'), PHP_EOL;

?>

See:

https://bugs.php.net/bug.php?id=31045
https://bugs.php.net/bug.php?id=30972
https://bugs.php.net/bug.php?id=69596
dkrnl at yandex dot ru 30-Sep-2013 02:58
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php
AllenJB 12-Oct-2012 08:09
<?php
$xml = json_decode(json_encode((array) simplexml_load_string($string)), 1);
?>

A reminder that json_encode attempts to convert data to UTF-8 without specific knowledge of the source encoding. This method can cause encoding issues if you're not working in UTF-8.
Anonymous 29-Feb-2012 08:54
Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/
Diego Araos, diego at klapmedia dot com 05-Feb-2011 12:57
A simpler way to transform the result into an array (requires json module).

<?php
function object2array($object) { return @json_decode(@json_encode($object),1); }
?>

Example:
<?php
$xml_object=simplexml_load_string('<SOME XML DATA');
$xml_array=object2array($xml_object);
?>
ascammon at hotmail dot com 28-Dec-2010 01:04
I had a hard time finding this documented, so posting it here in case it helps someone:

If you want to use multiple libxml options, separate them with a pipe, like so:

<?php
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
?>
jeff at creabilis dot com 17-Nov-2009 02:28
If you want to set the charset of the outputed xml, simply set the encoding attribute like this :

<?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?>

The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;.

Hope this help
Bob 17-Jun-2009 02:16
Here is my simple SimpleXML wrapper function.
As far as I can tell, it does the same as Julio Cesar Oliveira's (above).
It parses an XML string into a multi-dimensional associative array.
The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg).
<?php
function unserialize_xml($input, $callback = null, $recurse = false)
/* bool/array unserialize_xml ( string $input [ , callback $callback ] )
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
 * Returns false on all failure
 * Notes:
    * Root XML tags are stripped
    * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
    * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 */
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
    // Convert SimpleXMLElements to array
    if ($data instanceof SimpleXMLElement) $data = (array) $data;
    // Recurse into arrays
    if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
    // Run callback and return
    return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>
Julio Cesar Oliveira 30-Mar-2009 07:14
The XML2Array func now Recursive!

<?php
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }

    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}
?>
javalc6 at gmail dot com 18-Oct-2008 06:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.

Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.

<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>
rowan dot collins at gmail dot com 10-Jul-2008 07:07
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6

The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content.

<?php
$xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
    [0] => Text1 & XML entities
)
*/

$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?

// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
amir_abiri at ipcmedia dot com 08-Feb-2008 08:47
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} = $xml->number->{0} + 1;

echo $xml->asXml();
?>

echos:
<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>2</number></root>

However, this only works with a direct assignment, not with any of the other operators:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} += 1;
// Or:
$xml->number->{0}++;

echo $xml->asXml();
?>

Both of the above cases would result in:

<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>1<0/></number></root>
bojan 04-Feb-2008 04:38
As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect.
Consider the following:

<?php

// data in xml
$xml_txt = '
<root>
  <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>
  <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder>
</root>';

// load xml into SimpleXML object
$xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING

// see object structure
print_r($xml);

/* this prints
SimpleXMLElement Object
(
    [folder] => Array
        (
            [0] => aaaa
            [1] => bbbb
        )

)
*/

// but...
foreach ($xml->folder as $value){
    print_r($value);
}
/* prints complete structure of each folder element:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => aaaa
)

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => bbbb
)

*/
?>
hattori at hanso dot com 15-Oct-2007 03:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001

<?PHP
if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}
?>
nbijnens at servs dot eu 10-Sep-2007 05:17
Please note that not all LIBXML options are supported with the options argument.

For instance LIBXML_XINCLUDE does not work. But there is however a work around:

<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);

$xml->xinclude();
$xml = simplexml_import_dom($xml);

?>
Pedro 06-Jul-2007 01:28
Attention:

simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;).

Use numeric character references instead!
m dot ament at mailcity dot com 06-Mar-2007 06:51
Warning:

The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower 30-Jan-2007 03:03
A simple extension that adds a method for retrieving a specific attribute:

<?php
class simple_xml_extended extends SimpleXMLElement
{
    public    function    Attribute($name)
    {
        foreach($this->Attributes() as $key=>$val)
        {
            if($key == $name)
                return (string)$val;
        }
    }

}

$xml = simplexml_load_string('
<xml>
  <dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');

echo $xml->dog->Attribute('type');

?>

outputs 'poodle'

I prefer to use this technique rather than typecasting attributes.
Maciek Ruckgaber <maciekrb at gmai dot com> 07-Jun-2005 05:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P

when you have something like:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
?>

you will have the simpleXML object "transformed" to the text() content:

<?php
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328  (string)
?>
cellog at php dot net 31-Aug-2004 04:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx = simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
    if (is_string($val)) {
       // <one> will go here
    } elseif (is_array($val)) {
       // <multi> will go here because it happens multiple times
    } elseif (is_object($val)) {
      // <t> will go here because it contains tags
      // <two> will go here because it contains CDATA!
    }
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
    // this is not a tag that contains other tags
    $val = '' . $val;
    // now the CDATA is revealed magically.
}
?>


WDDX

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Beispiele
    • wddx examples
  • WDDX Funktionen
    • wddx_add_vars — Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu
    • wddx_deserialize — Deserialisiert ein WDDX Paket
    • wddx_packet_end — Schließt das WDDX-Paket mit der angegebenen ID
    • wddx_packet_start — Beginnt ein neues WDDX-Paket mit einer Struktur
    • wddx_serialize_value — Serialisiert einen einzelnen Wert in ein WDDX-Paket
    • wddx_serialize_vars — Serialisiert Variablen in ein WDDX-Paket

User Contributed Notes

There are no user contributed notes for this page.


Einführung

Warnung

This extension is DEPRECATED and UNBUNDLED as of PHP 7.4.0.

These functions are intended for work with » WDDX.

Warnung

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

User Contributed Notes

alvaro at demogracia dot com 29-Sep-2008 08:49
From OpenWDDX.Org:

"The Web Distributed Data Exchange, or WDDX, is a free, open XML-based technology that allows Web applications created with any platform to easily exchange data with one another over the Web."

"WDDX is an XML-based technology that enables the exchange of complex data between Web programming languages, creating what some refer to as 'Web syndicate networks'. WDDX consists of a language-independent representation of data based on an XML 1.0 DTD, and a set of modules for a wide variety of languages that use WDDX. WDDX can be used with HTTP, SMTP, POP, FTP and other Internet protocols that support transferring textual data."


Anforderungen

Diese Erweiterung erfordert die Erweiterung libxml. Das heißt, dass die Übergabe von --with-libxml, oder vor PHP 7.4.0 --enable-libxml, ebenfalls benötigt wird. Dies wird jedoch implizit erfüllt, da libxml standardmäßig aktiviert wird.

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP 7.4

Diese Erweiterung wurde ins » PECL-Repositorium verschoben und ist nicht mehr Teil von PHP ab PHP 7.4.0

Information zur Installation dieser PECL-Erweiterung finden sie im Kapitel Installation von PECL-Erweiterungen. Zusätzliche Informationen wie neue Releases, Downloads, Quelldateien, Maintainerinformation und ein CHANGELOG finden Sie hier: » https://pecl.php.net/package/wddx.

PHP < 7.4

After installing the required expat library, compile PHP with --enable-wddx, and use --with-libexpat-dir for expat.

Die Windowsversion von PHP enthält diese Erweiterung. Um diese Funktionen zu verwenden, müssen Sie keine zusätzlichen Erweiterungen aktivieren.

User Contributed Notes

There are no user contributed notes for this page.


Ressource-Typen

This extension defines a WDDX packet identifier returned by wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Beispiele

Inhaltsverzeichnis

  • wddx examples

User Contributed Notes

dormilich at netscape dot net 27-Nov-2008 06:37
If you want to use the WDDX 1.0 DTD for validation (http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt) check that you define the comment as element, not as attribute.

<?xml version="1.0" encoding="iso-8859-1" ?>
<wddxPacket version='1.0'>
    <header>
        <comment>PHP</comment>
    </header>
    <data><!-- WDDX serialized data --></data>
</wddxPacket>


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Beispiel #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Beispiel #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Hinweis:

Strings should be encoded in UTF-8; to handle other encodings, convert the string first using mb_convert_encoding(), UConverter::transcode(), or iconv().

User Contributed Notes

There are no user contributed notes for this page.


WDDX Funktionen

Inhaltsverzeichnis

  • wddx_add_vars — Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu
  • wddx_deserialize — Deserialisiert ein WDDX Paket
  • wddx_packet_end — Schließt das WDDX-Paket mit der angegebenen ID
  • wddx_packet_start — Beginnt ein neues WDDX-Paket mit einer Struktur
  • wddx_serialize_value — Serialisiert einen einzelnen Wert in ein WDDX-Paket
  • wddx_serialize_vars — Serialisiert Variablen in ein WDDX-Paket

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>


Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu

  • « WDDX Funktionen
  • wddx_deserialize »
  • PHP Manual
  • WDDX Funktionen
  • Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_add_vars(resource $packet_id, mixed $var_name, mixed ...$var_names): bool

Serialisiert die übergebenen Variablen und fügt das Ergebnis dem angegebenen Paket hinzu.

Parameter-Liste

Diese Funktion nimmt eine variable Anzahl von Parametern entgegen.

packet_id

Ein WDDX-Paket, wie von wddx_packet_start() zurückgeggeben.

var_name

Kann entweder eine Zeichenkette sein, die einen Variablennamen enthält, oder ein Array von Strings, die Variablennamen oder andere Arrays enthalten.

var_names

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

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 !


Deserialisiert ein WDDX Paket

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • WDDX Funktionen
  • Deserialisiert ein WDDX Paket

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Deserialisiert ein WDDX Paket

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_deserialize(string $packet): mixed

Deserialisiert ein WDDX Paket (packet).

Warnung

wddx_deserialize() dürfen keine Nutzereingaben aus nicht vertrauenswürdigen Quellen übergeben werden. Die Deserialisierung kann dazu führen, dass Code geladen und ausgeführt wird, aufgrund von Objekt-Instanziierung und Autoloading, und ein böswilliger Nutzer kann möglicherweise in der Lage sein, dies auszunutzen. Statt dessen ist ein sicheres, standardisiertes Daten-Austauschformat wie JSON (per json_decode() und json_encode()) zu verwenden, wenn serialisierte Daten von Benutzern empfangen werden müssen.

Parameter-Liste

packet

Ein WDDX-Paket als Zeichenkette oder Stream.

Rückgabewerte

Gibt den deserialisierten Wert zurück, der eine Zeichenkette, eine Zahl oder ein Array sein kann. Es ist zu beachten, dass Strukturen als assoziative Arrays deserialisiert werden.

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


Schließt das WDDX-Paket mit der angegebenen ID

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • WDDX Funktionen
  • Schließt das WDDX-Paket mit der angegebenen ID

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Schließt das WDDX-Paket mit der angegebenen ID

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_packet_end(resource $packet_id): string

Schließt das angegebene WDDX-Paket, und gibt es zurück.

Parameter-Liste

packet_id

Ein WDDX-Paket, wie von wddx_packet_start() zurückgegeben.

Rückgabewerte

Gibt die Zeichenkette zurück, die das WDDX-Paket enthält.

User Contributed Notes

There are no user contributed notes for this page.


Beginnt ein neues WDDX-Paket mit einer Struktur

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • WDDX Funktionen
  • Beginnt ein neues WDDX-Paket mit einer Struktur

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Beginnt ein neues WDDX-Paket mit einer Struktur

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_packet_start(string $comment = ?): resource

Beginnt ein neues WDDX-Paket für das inkrementelle Hinzufügen von Variablen. Es wird automatisch eine Strukturdefinition innerhalb des Pakets erzeugt, um die Variablen zu enthalten.

Parameter-Liste

comment

Eine optionale Kommentar-Zeichenkette.

Rückgabewerte

Gibt eine Paketkennung für die spätere Verwendung zurück, oder im Fehlerfall false.

User Contributed Notes

There are no user contributed notes for this page.


Serialisiert einen einzelnen Wert in ein WDDX-Paket

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • WDDX Funktionen
  • Serialisiert einen einzelnen Wert in ein WDDX-Paket

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serialisiert einen einzelnen Wert in ein WDDX-Paket

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_serialize_value(mixed $var, string $comment = ?): string

Erzeugt ein neues WDDX-Paket aus einem einzelnen angegebene Wert.

Parameter-Liste

var

Der zu serialisierende Wert.

comment

Eine optionale Kommentar-Zeichenkette, die im Paket-Header erscheint.

Rückgabewerte

Gibt das WDDX-Paket zurück, oder im Fehlerfall false.

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


Serialisiert Variablen in ein WDDX-Paket

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • WDDX Funktionen
  • Serialisiert Variablen in ein WDDX-Paket

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serialisiert Variablen in ein WDDX-Paket

Warnung

Diese Funktion wurde in PHP 7.4.0 ENTFERNT.

Beschreibung

wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string

Erzeugt ein WDDX-Paket mit einer Struktur, die die serialisierte Darstellung der übergebenen Variablen enthält.

Parameter-Liste

Diese Funktion nimmt eine variable Anzahl von Parametern entgegen.

var_name

Entweder einzelne Variablennamen oder Arrays mit Variablennamen bzw. weitere Arrays.

var_names

Rückgabewerte

Gibt das WDDX-Paket zurück, oder im Fehlerfall false.

Beispiele

Beispiel #1 wddx_serialize_vars()-Beispiel

<?php
$a = 1;
$b = 5.5;
$c = array("Blau", "Orange", "Lila");
$d = "Farben";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<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>Blau</string><string>Orange</string><string>Lilal</string></array></var>
<var name='d'><string>Farben</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

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
  • 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.


Einführung

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.


Anforderungen

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.


Installation

Diese » PECL-Erweiterung ist nicht Teil von PHP.

Information zur Installation dieser PECL-Erweiterung finden sie im Kapitel Installation von PECL-Erweiterungen. Zusätzliche Informationen wie neue Releases, Downloads, Quelldateien, Maintainerinformation und ein CHANGELOG finden Sie hier: » 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)

Einführung

Base abstract class for all the comparsion classes in the extension.

Klassenbeschreibung

class XMLDiff\Base {
/* Methoden */
public __construct(string $nsname)
abstract public diff(mixed $from, mixed $to): mixed
abstract public merge(mixed $src, mixed $diff): mixed
}

Inhaltsverzeichnis

  • 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

Beschreibung

public XMLDiff\Base::__construct(string $nsname)

Base constructor for all the worker classes in the xmldiff extension.

Parameter-Liste

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

Beschreibung

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.

Parameter-Liste

from

Source XML document.

to

Target XML document.

Rückgabewerte

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

Beschreibung

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.

Parameter-Liste

src

Source XML document.

diff

Document produced by the diff method.

Rückgabewerte

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

Einführung

Klassenbeschreibung

class XMLDiff\DOM extends XMLDiff\Base {
/* Methoden */
public diff(DOMDocument $from, DOMDocument $to): DOMDocument
public merge(DOMDocument $src, DOMDocument $diff): DOMDocument
/* Geerbte Methoden */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Inhaltsverzeichnis

  • 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

Beschreibung

public XMLDiff\DOM::diff(DOMDocument $from, DOMDocument $to): DOMDocument

Diff two DOMDocument instances and produce the new one containing the diff information.

Parameter-Liste

from

Source DOMDocument object.

to

Target DOMDocument object.

Rückgabewerte

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

Beschreibung

public XMLDiff\DOM::merge(DOMDocument $src, DOMDocument $diff): DOMDocument

Create new DOMDocument based on the diff.

Parameter-Liste

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

Rückgabewerte

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)

Einführung

Klassenbeschreibung

class XMLDiff\Memory extends XMLDiff\Base {
/* Methoden */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Geerbte Methoden */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Inhaltsverzeichnis

  • 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

Beschreibung

public XMLDiff\Memory::diff(string $from, string $to): string

Diff two strings containing XML documents and produce the diff information.

Parameter-Liste

from

Source XML document.

to

Target XML document.

Rückgabewerte

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

Beschreibung

public XMLDiff\Memory::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parameter-Liste

src

Source XML document.

diff

XML document containing diff information.

Rückgabewerte

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)

Einführung

Klassenbeschreibung

class XMLDiff\File extends XMLDiff\Base {
/* Methoden */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Geerbte Methoden */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Inhaltsverzeichnis

  • 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

Beschreibung

public XMLDiff\File::diff(string $from, string $to): string

Diff two local XML files and produce string with the diff information.

Parameter-Liste

from

Path to the source document.

to

Path to the target document.

Rückgabewerte

String with the XML document containing the diff information or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce merged XML document

  • « XMLDiff\File::diff
  • XML Parser »
  • PHP Manual
  • XMLDiff\File
  • Produce merged XML document

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce merged XML document

Beschreibung

public XMLDiff\File::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parameter-Liste

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

Rückgabewerte

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


XML Parser

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Event Handlers
  • Case Folding
  • Error Codes
  • Character Encoding
  • Beispiele
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • XML Parser Funktionen
    • xml_error_string — Get XML parser error string
    • 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 — Get XML parser error code
    • xml_parse_into_struct — Parse XML data into an array structure
    • xml_parse — Start parsing an XML document
    • xml_parser_create_ns — Create an XML parser with namespace support
    • xml_parser_create — Create an XML parser
    • xml_parser_free — Free an XML parser
    • xml_parser_get_option — Get options from an XML parser
    • xml_parser_set_option — Set options in an XML parser
    • 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.


Einführung

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at » http://www.w3.org/XML/.

This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.

This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.

User Contributed Notes

There are no user contributed notes for this page.


Anforderungen

Diese Erweiterung erfordert die Erweiterung libxml. Das heißt, dass die Übergabe von --with-libxml, oder vor PHP 7.4.0 --enable-libxml, ebenfalls benötigt wird. Dies wird jedoch implizit erfüllt, da libxml standardmäßig aktiviert wird.

This extension uses an expat compat layer by default. It can use also expat, which can be found at » https://libexpat.github.io/. 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 » https://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Diese Erweiterung ist standardmäßig aktiviert. Sie kann bei der Kompilierung mit der folgenden Option ausgeschaltet werden: --disable-xml

These functions are enabled by default, using the bundled expat library. You can disable XML support with --disable-xml. If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. If you don't want to use the bundled expat library, configure PHP with --with-expat-dir=DIR, where DIR should point to the base installation directory of expat.

Die Windowsversion von PHP enthält diese Erweiterung. Um diese Funktionen zu verwenden, müssen Sie keine zusätzlichen Erweiterungen aktivieren.

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.


Ressource-Typen

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.


Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

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)
Enthält die SAX Implementierungsmethode. Kann libxml oder expat sein.

User Contributed Notes

There are no user contributed notes for this page.


Event Handlers

The XML event handlers defined are:

Supported XML handlers
PHP function to set handler | Event description
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant.
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved.
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity.
xml_set_notation_decl_handler() | This handler is called for declaration of a notation.
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.
xml_set_start_namespace_decl_handler() | This handler is called for the start of a namespace declaration.
xml_set_end_namespace_decl_handler() | This handler is called for the end of a namespace declaration. Note that this event is not triggered by 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.


Error Codes

Die folgenden Konstanten sind für XML Fehler-Codes definiert (wie von xml_parse() zurückgegeben):

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


Character Encoding

PHP's XML extension supports the » Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.

Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.

Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.

If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.

If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.

User Contributed Notes

There are no user contributed notes for this page.


Beispiele

Inhaltsverzeichnis

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

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

Beispiel #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.)

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

?>

Beispiel #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:

Beispiel #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>

User Contributed Notes

There are no user contributed notes for this page.


XML Parser Funktionen

Inhaltsverzeichnis

  • xml_error_string — Get XML parser error string
  • 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 — Get XML parser error code
  • xml_parse_into_struct — Parse XML data into an array structure
  • xml_parse — Start parsing an XML document
  • xml_parser_create_ns — Create an XML parser with namespace support
  • xml_parser_create — Create an XML parser
  • xml_parser_free — Free an XML parser
  • xml_parser_get_option — Get options from an XML parser
  • xml_parser_set_option — Set options in an XML parser
  • 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.


Get XML parser error string

  • « XML Parser Funktionen
  • xml_get_current_byte_index »
  • PHP Manual
  • XML Parser Funktionen
  • Get XML parser error string

xml_error_string

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

xml_error_string — Get XML parser error string

Beschreibung

xml_error_string(int $error_code): ?string

Gets the XML parser error string associated with the given error_code.

Parameter-Liste

error_code

An error code from xml_get_error_code().

Rückgabewerte

Returns a string with a textual description of the error error_code, or null if no description was found.

Siehe auch

  • xml_get_error_code() - Get XML parser error code

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
  • XML Parser Funktionen
  • 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

Beschreibung

xml_get_current_byte_index(XMLParser $parser): int

Gets the current byte index of the given XML parser.

Parameter-Liste

parser

A reference to the XML parser to get byte index from.

Rückgabewerte

Returns which byte index the parser is currently at in its data buffer (starting at 0).

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Anmerkungen

Warnung

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

Siehe auch

  • 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
  • XML Parser Funktionen
  • 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

Beschreibung

xml_get_current_column_number(XMLParser $parser): int

Gets the current column number of the given XML parser.

Parameter-Liste

parser

A reference to the XML parser to get column number from.

Rückgabewerte

Returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Siehe auch

  • 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
  • XML Parser Funktionen
  • 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

Beschreibung

xml_get_current_line_number(XMLParser $parser): int

Gets the current line number for the given XML parser.

Parameter-Liste

parser

A reference to the XML parser to get line number from.

Rückgabewerte

Returns which line the parser is currently at in its data buffer.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Siehe auch

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


Get XML parser error code

  • « xml_get_current_line_number
  • xml_parse_into_struct »
  • PHP Manual
  • XML Parser Funktionen
  • Get XML parser error code

xml_get_error_code

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

xml_get_error_code — Get XML parser error code

Beschreibung

xml_get_error_code(XMLParser $parser): int

Gets the XML parser error code.

Parameter-Liste

parser

A reference to the XML parser to get error code from.

Rückgabewerte

Returns one of the error codes listed in the error codes section.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Siehe auch

  • xml_error_string() - Get XML parser error string

User Contributed Notes

There are no user contributed notes for this page.


Parse XML data into an array structure

  • « xml_get_error_code
  • xml_parse »
  • PHP Manual
  • XML Parser Funktionen
  • Parse XML data into an array structure

xml_parse_into_struct

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

xml_parse_into_struct — Parse XML data into an array structure

Beschreibung

xml_parse_into_struct(
XMLParser $parser,
string $data,
array &$values,
array &$index = null
): int

This function parses an XML string into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.

Parameter-Liste

parser

A reference to the XML parser.

data

A string containing the XML data.

values

An array containing the values of the XML data

index

An array containing pointers to the location of the appropriate values in the $values.

Rückgabewerte

xml_parse_into_struct() returns 0 for failure and 1 for success. This is not the same as false and true, be careful with operators such as ===.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Beispiele

Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embedded inside a para tag, and then we parse this and print out the structures generated:

Beispiel #1 xml_parse_into_struct() example

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

When we run that code, the output will be:

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
        )

)

Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being traversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:

Beispiel #2 moldb.xml - small database of molecular information

<?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>
And some code to parse the document and generate the appropriate objects:

Beispiel #3 parsemoldb.php - parses moldb.xml into an array of molecular objects

<?php

class AminoAcid {
var $name; // aa name
var $symbol; // three letter symbol
var $code; // one letter code
var $type; // hydrophobic, charged or neutral

function __construct ($aa)
{
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}

function readDatabase($filename)
{
// read the XML database of aminoacids
$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);

// loop through the structures
foreach ($tags as $key=>$val) {
if ($key == "molecule") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}

function parseMol($mvalues)
{
for ($i=0; $i < count($mvalues); $i++) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
After executing parsemoldb.php, the variable $db contains an array of AminoAcid objects, and the output of the script confirms that:
** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

User Contributed Notes

Adam Tylmad 30-Apr-2009 12:58
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
aerik at thesylvans dot com 28-Nov-2008 03:55
Here's another attempt at dealing with rebuilding the xml from the array.  I'm basically preventing certain tags from being self closing by just checking for them explicitly (sure wish expat didn't interpret <textarea /> and <textarea></textarea> the same way (as "complete" tags).

<?php
function array2xml($xmlary){
  $o='';
  foreach($xmlary as $tag ){
    if($tag['tag'] == 'textarea' && !isset($tag['value'])){
      //fake a value so it won't self close
      $tag['value']='';
    }
    //tab space:
    $t = '';
    for($i=1; $i < $tag['level'];$i++){
      $t.="\t";
    }
    switch($tag['type']){
      case 'complete':
      case 'open':
        $o.=$t.'<'.$tag['tag'];
        if(isset($tag['attributes'])){
          foreach($tag['attributes'] as $attr=>$aval){
            $o.=' '.$attr.'="'.$aval.'"';
          }//foreach
        }//attributes
        if($tag['type'] == 'complete'){
          if(!isset($tag['value'])){
            $o .= ' />'."\n";
          } else {
            $o .= '>'."\n".$t.$tag['value']."\n".$t.'</'.$tag['tag'].'>'."\n";
          }
        }else{
          $o .= '>'."\n";
        }
        break;
      case 'close':
        $o .= $t.'</'.$tag['tag'].'>'."\n";
        break;
      case 'cdata':
        $o .= $t.$tag['value']."\n";
        break;
    }//switch
  }//foreach
}
?>
dale at ucsc dot edu 25-Sep-2008 04:16
here you can [re]assemble xml from a xml_parse_into_struct generated array: ie array2xml

<?php
$xml_parser = xml_parser_create( 'UTF-8' ); // UTF-8 or ISO-8859-1
xml_parser_set_option( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $xml_parser, $my_text_xml, $aryXML );
xml_parser_free($xml_parser);

//now use aryXML array to xml string:
        $o='';
        foreach( $aryXML as $tag ){
            //tab space:
            for($i=1; $i < $tag['level'];$i++)
                $o.="\t";
            if($tag['type']!='close'){
                if($tag['type']!='cdata')
                    $o.='<'.$tag['tag'];
                if(isset($tag['attributes'])){
                    foreach($tag['attributes'] as $attr=>$aval){
                        $o.=' '.$attr.'="'.$aval.'"';
                    }
                }
                if($tag['type']!='cdata'){
                    $o.=($tag['type']=='complete')?'/>'."\n":'>'."\n";
                }
                $o.=(isset($tag['value']))?$tag['value']:'';
            }else{
                $o.='</'.$tag['tag'].'>';
            }
        }
?>
Llorenc 09-Sep-2008 03:20
Sorry, forgot my last post below, I confused CDATA sections (<![CDATA[]]>) with the value type "cdata", which despite its name it's very different! The first allows adding markup (&,<,>) as regular text and the second is to indicate a not complete node between the open and close nodes. What is true is that the CDATA delimiters are lost after xml_parse_into_struct so it's not possible to revert the process.

Please, feel free to remove my comments or leave them if you think they can help anyone.
wickedfather at hotmail dot com 06-Jul-2008 12:33
Had a comment up that was removed saying I'd found drawbacks, but here's a class what I wrote which works fine for me.  Comments removed due to post restrictions.  Pass the xml into the parse method or in the constructor.  Php4 and 5 safe.

class XMLThing
{
    var $rawXML;
    var $valueArray = array();
    var $keyArray = array();
    var $parsed = array();
    var $index = 0;
    var $attribKey = 'attributes';
    var $valueKey = 'value';
    var $cdataKey = 'cdata';
    var $isError = false;
    var $error = '';

    function XMLThing($xml = NULL)
    {
        $this->rawXML = $xml;
    }

    function parse($xml = NULL)
    {
        if (!is_null($xml))
        {
            $this->rawXML = $xml;
        }

        $this->isError = false;

        if (!$this->parse_init())
        {
            return false;
        }

        $this->index = 0;
        $this->parsed = $this->parse_recurse();
        $this->status = 'parsing complete';

        return $this->parsed;
    }

    function parse_recurse()
    {
        $found = array();
        $tagCount = array();

        while (isset($this->valueArray[$this->index]))
        {
            $tag = $this->valueArray[$this->index];
            $this->index++;

            if ($tag['type'] == 'close')
            {
                return $found;
            }

            if ($tag['type'] == 'cdata')
            {
                $tag['tag'] = $this->cdataKey;
                $tag['type'] = 'complete';
            }

            $tagName = $tag['tag'];

            if (isset($tagCount[$tagName]))
            {
                if ($tagCount[$tagName] == 1)
                {
                    $found[$tagName] = array($found[$tagName]);
                }

                $tagRef =& $found[$tagName][$tagCount[$tagName]];
                $tagCount[$tagName]++;
            }
            else
            {
                $tagCount[$tagName] = 1;
                $tagRef =& $found[$tagName];
            }

            switch ($tag['type'])
            {
                case 'open':
                    $tagRef = $this->parse_recurse();

                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                    }

                    if (isset($tag['value']))
                    {
                        if (isset($tagRef[$this->cdataKey]))
                        {
                            $tagRef[$this->cdataKey] = (array)$tagRef[$this->cdataKey];
                            array_unshift($tagRef[$this->cdataKey], $tag['value']);
                        }
                        else
                        {
                            $tagRef[$this->cdataKey] = $tag['value'];
                        }
                    }
                    break;

                case 'complete':
                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                        $tagRef =& $tagRef[$this->valueKey];
                    }

                    if (isset($tag['value']))
                    {
                        $tagRef = $tag['value'];
                    }
                    break;
            }
        }

        return $found;
    }

    function parse_init()
    {
        $this->parser = xml_parser_create();

        $parser = $this->parser;
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        if (!$res = (bool)xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray))
        {
            $this->isError = true;
            $this->error = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
        }
        xml_parser_free($parser);

        return $res;
    }
}
jemptymethod at gmail dot com 16-Jun-2008 01:39
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is "great"....First of all, it doesn't handle attributes.  Second of all, as my code below demonstrates, there is no need waste processing by determining duplicates within their own loop.  Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.

Here is some much more consise code, though not (yet) object oriented, and also not yet handling attributes; it maintains a stack for each level:

<?php
function xml_parse_into_assoc($file) {
  $data = implode("", file($file));
  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);

  xml_parse_into_struct($p, $data, $vals, $index);
  xml_parser_free($p);

  $levels = array(null);

  foreach ($vals as $val) {
    if ($val['type'] == 'open' || $val['type'] == 'complete') {
      if (!array_key_exists($val['level'], $levels)) {
        $levels[$val['level']] = array();
      }
    }

    $prevLevel =& $levels[$val['level'] - 1];
    $parent = $prevLevel[sizeof($prevLevel)-1];

    if ($val['type'] == 'open') {
      $val['children'] = array();
      array_push(&$levels[$val['level']], $val);
      continue;
    }

    else if ($val['type'] == 'complete') {
      $parent['children'][$val['tag']] = $val['value'];
    }

    else if ($val['type'] == 'close') {
      $pop = array_pop($levels[$val['level']]);
      $tag = $pop['tag'];

      if ($parent) {
        if (!array_key_exists($tag, $parent['children'])) {
          $parent['children'][$tag] = $pop['children'];
        }
        else if (is_array($parent['children'][$tag])) {
          $parent['children'][$tag][] = $pop['children'];
        }
      }
      else {
        return(array($pop['tag'] => $pop['children']));
      }
    }

    $prevLevel[sizeof($prevLevel)-1] = $parent;
  }
}
?>
wickedfather at hotmail dot com 12-Apr-2008 08:36
To beaudurrant - that class is great and structures things in a very sensible way.  Only problem is that it raises an error if a tag is empty, so would suggest a simple mod to the parse method just to add an isset test.

if (isset($val['value']))
{
    $this->setArrayValue($this->output, $stack, $val['value']);
}
mathiasrav at gmail dot com 10-Mar-2008 08:42
In response to Anonymous' post at 26-Feb-2008 11:50:

Saying that you "don't understand everything" isn't going to get you very popular - you should understand the code you use.
foreach isn't *slow* in PHP, it is actually faster than the equivalent for-construct (which, in many cases, isn't available).

The reason your script is slow is simply your use of xml_parse_into_struct - it reads the whole XML-string and doesn't return until it has parsed and validated it all. If you're looking for efficiency, you'll have to use the more low-level xml_parser_create, xml_set_*_handler functions. Then make sure you don't keep everything in a huge array before outputting it (at least don't if you're going for efficiency).
beaudurrant at gmail dot com 19-Dec-2007 11:23
This is extending what Alf Marius Foss Olsen had posted above.

It takes into account array keys with the same name and uses an increment for them instead of overwriting the keys.

I am using it for SOAP requests (20K - 150K) and it parses very fast compared to PEAR.

<?

class XMLParser  {

    // raw xml
    private $rawXML;
    // xml parser
    private $parser = null;
    // array returned by the xml parser
    private $valueArray = array();
    private $keyArray = array();

    // arrays for dealing with duplicate keys
    private $duplicateKeys = array();

    // return data
    private $output = array();
    private $status;

    public function XMLParser($xml){
        $this->rawXML = $xml;
        $this->parser = xml_parser_create();
        return $this->parse();
    }

    private function parse(){

        $parser = $this->parser;

        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);     // Dont bother with empty info
        if(!xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray)){
            $this->status = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
            return false;
        }
        xml_parser_free($parser);

        $this->findDuplicateKeys();

        // tmp array used for stacking
        $stack = array();
        $increment = 0;

        foreach($this->valueArray as $val) {
            if($val['type'] == "open") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack, $val['tag']);
                }
            } elseif($val['type'] == "close") {
                array_pop($stack);
                // reset the increment if they tag does not exists in the stack
                if(array_key_exists($val['tag'], $stack)){
                    $this->duplicateKeys[$val['tag']] = 0;
                }
            } elseif($val['type'] == "complete") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack,  $val['tag']);
                }
                $this->setArrayValue($this->output, $stack, $val['value']);
                array_pop($stack);
            }
            $increment++;
        }

        $this->status = 'success: xml was parsed';
        return true;

    }

    private function findDuplicateKeys(){

        for($i=0;$i < count($this->valueArray); $i++) {
            // duplicate keys are when two complete tags are side by side
            if($this->valueArray[$i]['type'] == "complete"){
                if( $i+1 < count($this->valueArray) ){
                    if($this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'] && $this->valueArray[$i+1]['type'] == "complete"){
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                    }
                }
            }
            // also when a close tag is before an open tag and the tags are the same
            if($this->valueArray[$i]['type'] == "close"){
                if( $i+1 < count($this->valueArray) ){
                    if(    $this->valueArray[$i+1]['type'] == "open" && $this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'])
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                }
            }

        }

    }

    private function setArrayValue(&$array, $stack, $value){
        if ($stack) {
            $key = array_shift($stack);
            $this->setArrayValue($array[$key], $stack, $value);
            return $array;
        } else {
            $array = $value;
        }
    }

    public function getOutput(){
        return $this->output;
    }

    public function getStatus(){
        return $this->status;
    }

}

?>

Usage:

$p = new XMLParser($xml);
$p->getOutput();
Alf Marius Foss Olsen 12-Sep-2007 06:46
<?php
/*
  An easy lightweight (Array ->) XML -> Array algorithm..

  Typical case: You have an array you want to export to an external server,
                so you make XML out of it, exports it, and "on the other side"
                make it into an array again. These two functions will take care
                of that last part, ie XML -> Array

  NOTE! The function XMLToArray assumes that the XML _dont_ have nodes on the
        same level with the same name, then it just wont work. This is not a
        problem, as this case deals with Array -> XML -> Array, and an array
        cant have to identical indexes/keys.
*/

function XMLToArray($xml) {
  $parser = xml_parser_create('ISO-8859-1'); // For Latin-1 charset
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); // Dont bother with empty info
  xml_parse_into_struct($parser, $xml, $values);
  xml_parser_free($parser);

  $return = array(); // The returned array
  $stack = array(); // tmp array used for stacking
  foreach($values as $val) {
    if($val['type'] == "open") {
      array_push($stack, $val['tag']);
    } elseif($val['type'] == "close") {
      array_pop($stack);
    } elseif($val['type'] == "complete") {
      array_push($stack, $val['tag']);
      setArrayValue($return, $stack, $val['value']);
      array_pop($stack);
    }//if-elseif
  }//foreach
  return $return;
}//function XMLToArray

function setArrayValue(&$array, $stack, $value) {
  if ($stack) {
    $key = array_shift($stack);
    setArrayValue($array[$key], $stack, $value);
    return $array;
  } else {
    $array = $value;
  }//if-else
}//function setArrayValue

// USAGE:
$xml = <<<QQQ
<?xml version="1.0"?>
<root>
  <node1>Some text</node1>
  <node2a>
    <node2b>
      <node2c>Some text</node2c>
    </node2b>
  </node2a>
</root>\n
QQQ;
$array = XMLToArray($xml);
print "<pre>";
print_r($array);
print "</pre>";
//  Output:
//
//  Array
//  (
//      [root] => Array
//          (
//              [node1] => Some text
//              [node2a] => Array
//                  (
//                      [node2b] => Array
//                          (
//                              [node2c] => Some text
//                          )
//                  )
//          )
//  )
?>
vinod at citadel-soft dot com 01-Sep-2007 03:43
My previous code was having some bugs in, that is fixed now

<?php
class CSLXmlReader {
    private $tagstack;
    private $xmlvals;
    private  $xmlvarArrPos;
    private $xmlfile;
    function __construct($filename)  // constructor to intialize the stack and val array
    {

        $this->tagstack = array();   // contain the open tags till now
        $this->xmlvals = array();
        $this->xmlvarArrPos = $this->xmlvals;  // temporary variable to hold the current tag position
        $this->xmlfile = $filename;
    }
    function readDatabase()
    {
        // read the XML database
        $data = implode("", file($this->xmlfile));
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $data, $values, $tags);
        xml_parser_free($parser);

        foreach($values as $key => $val)  //
        {
            if($val['type'] == "open")
            {
                array_push($this->tagstack, $val['tag']);
                $this->getArrayPath();
                if(count($this->xmlvarArrPos) > 0 && (!array_key_exists(0,$this->xmlvarArrPos)))
                {
                    $temp1 = $this->xmlvarArrPos;
                    $this->xmlvarArrPos =  array();
                    $this->xmlvarArrPos[0] = $temp1;
                    array_push($this->tagstack, 1);
                }
                else if( array_key_exists(0,$this->xmlvarArrPos)){
                    $opncount = count($this->xmlvarArrPos);
                    array_push($this->tagstack, $opncount);
                }
                $tagStackPointer += 1;
            }else if($val['type'] == "close")
            {
                while( $val['tag'] != ($lastOpened = array_pop($this->tagstack))){}
            }else if($val['type'] ==  "complete")
            {
                $this->getArrayPath();
                if( array_key_exists($val['tag'],$this->xmlvarArrPos))
                {
                    if(array_key_exists(0,$this->xmlvarArrPos[$val['tag']]))
                    {
                        $elementCount = count($this->xmlvarArrPos[$val['tag']]);
                        $this->xmlvarArrPos[$val['tag']][$elementCount] = $val['value'];
                    }else
                    {
                        $temp1 = $this->xmlvarArrPos[$val['tag']];
                        $this->xmlvarArrPos[$val['tag']] =  array();
                        $this->xmlvarArrPos[$val['tag']][0] = $temp1;
                        $this->xmlvarArrPos[$val['tag']][1] = $val['value'];
                    }
                } else
                {
                    $this->xmlvarArrPos[$val['tag']] = $val['value'];
                }
            }
        }
        reset($this->xmlvals);
        return $this->xmlvals;
    }
    function getArrayPath()
    {

        reset($this->xmlvals);
        $this->xmlvarArrPos = &$this->xmlvals;
        foreach($this->tagstack as $key)
        {
            $this->xmlvarArrPos = &$this->xmlvarArrPos[$key];

        }
    }

}

$readerObj  = new CSLXmlReader("test.xml");
$xmlvals = $readerObj->readDatabase();

echo "########## XML Values In array as the multidimentional array  #############\n";
echo "<pre>";
print_r($xmlvals);
echo "</pre>";

?>
siteres at gmail dot com 07-Feb-2007 01:38
PHP: XML to Array and backwards:

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Sources are here:
http://mysrc.blogspot.com/2007/02/php-xml-to-array-and-backwards.html
(leave me comments:)

Example #1 (1.xml):

<ddd>
 <onemore dd="55">
  <tt>333</tt>
  <tt ss="s1">555</tt>
  <tt>777</tt>
 </onemore>
 <two>sdf rr</two>
</ddd>

The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);

Here is the Array result:

Array
(
   [ddd] => Array (
           [_c] => Array (
                   [_p] => Array *RECURSION*
                   [onemore] => Array (
                           [_a] => Array (
                                   [dd] => 55
                               )
                           [_c] => Array (
                                   [_p] => Array  *RECURSION*
                                   [tt] => Array (
                                           [0] => Array (
                                                   [_v] => 333
                                               )
                                           [1] => Array (
                                                   [_a] => Array (
                                                           [ss] => s1
                                                       )
                                                   [_v] => 555
                                               )
                                           [2] => Array (
                                                   [_v] => 777
                                               )
                                       )
                               )
                       )
                   [two] => Array (
                           [_v] => sdf rr
                       )
               )
       )
)
webmaster at after5webdesign dot com 30-Nov-2006 04:48
That parser also has a problem in which it will not parse more items than the current level it is on. That is, parsing this:  <1><2>A</2><2>B</2><2>C</2></1>
Will only result in this: A B
C is never processed.

It might be better with something like this:
          $file = get_url('http://news.search.yahoo.com/news/rss?p=current+events', URL_CONTENT);
          $data = $file['content'];
          $xml_parser = xml_parser_create();
          xml_parse_into_struct($xml_parser, $data, $vals, $index);
          xml_parser_free($xml_parser);
          //Uncomment the lines below to see the entire structure of your XML document
          //echo "<pre>INDEX: \n";
          //print_r ($index);
          //echo "\n \n \n VALUES:";
          //print_r ($vals);
          //echo "</pre>";
          $params = array();
          $level = array();
          $start_level = 1;
          foreach ($vals as $xml_elem) {
            if ($xml_elem['type'] == 'open') {
              if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
              } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
              }
            }
            if ($xml_elem['type'] == 'complete') {
              $php_stmt = '$params';
              while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
              }
              $php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';
              eval($php_stmt);
              $start_level--;
            }
          }
          echo "<pre>";
          print_r ($params);
          echo "</pre>";

~Tim_Myth
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
  • XML Parser Funktionen
  • Start parsing an XML document

xml_parse

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

xml_parse — Start parsing an XML document

Beschreibung

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.

Parameter-Liste

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.

Rückgabewerte

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

Hinweis:

Some errors (such as entity errors) are reported at the end of the data, thus only if is_final is set and true.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Beispiele

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


Create an XML parser with namespace support

  • « xml_parse
  • xml_parser_create »
  • PHP Manual
  • XML Parser Funktionen
  • Create an XML parser with namespace support

xml_parser_create_ns

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

xml_parser_create_ns — Create an XML parser with namespace support

Beschreibung

xml_parser_create_ns(?string $encoding = null, string $separator = ":"): XMLParser

xml_parser_create_ns() creates a new XML parser with XML namespace support and returns a XMLParser instance to be used by the other XML functions.

Parameter-Liste

encoding

The input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. The default output charset is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

separator

With a namespace aware parser tag parameters passed to the various handler functions will consist of namespace and tag name separated by the string specified in separator.

Rückgabewerte

Returns a new XMLParser instance.

Changelog

Version | Beschreibung
8.0.0 | This function returns an XMLParser instance now; previously, a resource was returned, Bei einem Fehler wird false zurückgegeben..
8.0.0 | encoding is nullable now.

Siehe auch

  • xml_parser_create() - Create an XML parser
  • xml_parser_free() - Free an XML parser

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.


Create an XML parser

  • « xml_parser_create_ns
  • xml_parser_free »
  • PHP Manual
  • XML Parser Funktionen
  • Create an XML parser

xml_parser_create

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

xml_parser_create — Create an XML parser

Beschreibung

xml_parser_create(?string $encoding = null): XMLParser

xml_parser_create() creates a new XML parser and returns a XMLParser instance to be used by the other XML functions.

Parameter-Liste

encoding

The input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. If empty string is passed, the parser attempts to identify which encoding the document is encoded in by looking at the heading 3 or 4 bytes. The default output charset is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

Rückgabewerte

Returns a new XMLParser instance.

Changelog

Version | Beschreibung
8.0.0 | This function returns an XMLParser instance now; previously, a resource was returned, Bei einem Fehler wird false zurückgegeben..
8.0.0 | encoding is nullable now.

Siehe auch

  • xml_parser_create_ns() - Create an XML parser with namespace support
  • xml_parser_free() - Free an XML parser

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.


Free an XML parser

  • « xml_parser_create
  • xml_parser_get_option »
  • PHP Manual
  • XML Parser Funktionen
  • Free an XML parser

xml_parser_free

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

xml_parser_free — Free an XML parser

Beschreibung

xml_parser_free(XMLParser $parser): bool

Hinweis:

Diese Funktion hat keine Auswirkung. Vor PHP 8.0.0 wurde sie verwendet, um die Ressource zu schließen.

Frees the given XML parser.

Achtung

In addition to calling xml_parser_free() when the parsing is finished, prior to PHP 8.0.0, it was necessary to also explicitly unset the reference to parser to avoid memory leaks, if the parser resource is referenced from an object, and this object references that parser resource.

Parameter-Liste

parser
A reference to the XML parser to free.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

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!


Get options from an XML parser

  • « xml_parser_free
  • xml_parser_set_option »
  • PHP Manual
  • XML Parser Funktionen
  • Get options from an XML parser

xml_parser_get_option

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

xml_parser_get_option — Get options from an XML parser

Beschreibung

xml_parser_get_option(XMLParser $parser, int $option): string|int|bool

Gets an option value from an XML parser.

Parameter-Liste

parser
A reference to the XML parser to get an option from.
option
Which option to fetch. XML_OPTION_CASE_FOLDING, XML_OPTION_SKIP_TAGSTART, XML_OPTION_SKIP_WHITE and XML_OPTION_TARGET_ENCODING are available. See xml_parser_set_option() for their description.

Rückgabewerte

Returns the option's value.

Fehler/Exceptions

Throws a ValueError when an invalid value is passed to option.

Prior to PHP 8.0.0, passing an invalid value to option generated a E_WARNING as well as making the function return false.

Changelog

Version | Beschreibung
8.3.0 | The function now returns a boolean for boolean options.
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.
8.0.0 | A ValueError is now thrown if option is invalid.
7.1.24, 7.2.12, 7.3.0 | options now supports XML_OPTION_SKIP_TAGSTART and 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);
?>


Set options in an XML parser

  • « xml_parser_get_option
  • xml_set_character_data_handler »
  • PHP Manual
  • XML Parser Funktionen
  • Set options in an XML parser

xml_parser_set_option

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

xml_parser_set_option — Set options in an XML parser

Beschreibung

xml_parser_set_option(XMLParser $parser, int $option, string|int|bool $value): bool

Sets an option in an XML parser.

Parameter-Liste

parser

A reference to the XML parser to set an option in.

option

Which option to set. See below.

The following options are available:

XML parser options
Option constant | Data type | Description
XML_OPTION_CASE_FOLDING | bool | Controls whether case-folding is enabled for this XML parser. Enabled by default.
XML_OPTION_SKIP_TAGSTART | integer | Specify how many characters should be skipped in the beginning of a tag name.
XML_OPTION_SKIP_WHITE | bool | Whether to skip values consisting of whitespace characters.
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser.By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

value

The option's new value.

Rückgabewerte

Returns true on success or false on failure.

Fehler/Exceptions

Throws a ValueError when an invalid value is passed to option.

Prior to PHP 8.0.0, the function returned false when passing an invalid value to option generated a E_WARNING as well as making the function return false.

Changelog

Version | Beschreibung
8.3.0 | The value parameter now also accepts booleans. The options XML_OPTION_CASE_FOLDING and XML_OPTION_SKIP_WHITE are now boolean options.
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.
8.0.0 | A ValueError is now thrown if option is invalid.

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
  • XML Parser Funktionen
  • 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

Beschreibung

xml_set_character_data_handler(XMLParser $parser, callable $handler): true

Sets the character data handler function for the XML parser parser.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
Der XML-Parser, der den Handler aufruft.
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).

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

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
  • XML Parser Funktionen
  • Set up default handler

xml_set_default_handler

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

xml_set_default_handler — Set up default handler

Beschreibung

xml_set_default_handler(XMLParser $parser, callable $handler): true

Sets the default handler function for the XML parser parser.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
Der XML-Parser, der den Handler aufruft.
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.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

User Contributed Notes

jp dot amarok at email dot cz 22-Apr-2024 04:00
For anyone who was also wondering what kind of events this function actually handles:

it's used in cases when an XML comment is found or an additional declaration like an xml-stylesheet. In such cases the data argument contains the whole string as it is, for example:

<!-- this is a comment -->
<?xml-stylesheet title="mystyle" type="text/xsl" href="style.xsl" ?>
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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Parameter-Liste

parser

Der XML-Parser

start_handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

start_element_handler(XMLParser $parser, string $name, array $attributes): void
parser
Der XML-Parser, der den Handler aufruft.
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

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

end_element_handler(XMLParser $parser, string $name): void
parser
Der XML-Parser, der den Handler aufruft.
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.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Achtung

This event is not supported under libXML, so a registered handler wouldn't be called.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix)
parser
Der XML-Parser, der den Handler aufruft.
prefix
The prefix is a string used to reference the namespace within an XML object. false if no prefix exists.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Siehe auch

  • 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
  • XML Parser Funktionen
  • 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

Beschreibung

xml_set_external_entity_ref_handler(XMLParser $parser, callable $handler): true

Sets the external entity reference handler function for the XML parser parser.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

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
Der XML-Parser, der den Handler aufruft.
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.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.
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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

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
Der XML-Parser, der den Handler aufruft.
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.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Parameter-Liste

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Beispiele

Beispiel #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>");
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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
  • XML Parser Funktionen
  • 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

Beschreibung

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

Achtung

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.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

handler(XMLParser $parser, string $target, string $data): void
parser
Der XML-Parser, der den Handler aufruft.
target
The processing instruction target.
data
The processing instruction data.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix, string $uri): void
parser
Der XML-Parser, der den Handler aufruft.
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.

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

Siehe auch

  • 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
  • XML Parser Funktionen
  • 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

Beschreibung

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.

Parameter-Liste

parser

Der XML-Parser

handler

Wenn null oder eine leere Zeichenkette übergeben wird, wird der Handler auf seinen Standardzustand zurückgesetzt.

Wenn handler vom Typ callable ist, wird das Callable als Handler gesetzt.

Wenn handler vom Typ string ist, kann es der Name der Methode eines Objekts sein, das mit xml_set_object() gesetzt wurde.

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
Der XML-Parser, der den Handler aufruft.
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()).

Rückgabewerte

Gibt immer true zurück.

Changelog

Version | Beschreibung
8.0.0 | parser erwartet nun eine XMLParser-Instanz; vorher wurde eine gültige xml-Ressource erwartet.

User Contributed Notes

There are no user contributed notes for this page.


The XMLParser class

(PHP 8)

Einführung

A fully opaque class which replaces xml resources as of PHP 8.0.0.

Klassenbeschreibung

final class XMLParser {
}

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • XMLReader — Die Klasse XMLReader
    • XMLReader::close — Beendet die XMLReader-Eingabe
    • XMLReader::expand — Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück
    • XMLReader::getAttribute — Liefert den Wert eines Attributes nach Namen
    • XMLReader::getAttributeNo — Gibt den Wert eines Attributes nach Position zurück
    • XMLReader::getAttributeNs — Gibt den Wert eines Attributes nach lokalem Namen und URI zurück
    • XMLReader::getParserProperty — Zeigt an, ob die angegebene Eigenschaft gesetzt wurde
    • XMLReader::isValid — Zeigt an, ob das geparste Dokument valide ist
    • XMLReader::lookupNamespace — Prüft, ob ein Namensbereich für einen Präfix vorhanden ist
    • XMLReader::moveToAttribute — Zeiger auf benanntes Attribut setzen
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader->moveToElement — Zeiger positionieren auf das Elternelement des aktuellen Attributes
    • XMLReader::moveToFirstAttribute — Zeiger auf erstes Attribut setzen
    • XMLReader::moveToNextAttribute — Zeiger auf nächstes Attribut setzen
    • XMLReader::next — Zeiger auf nächstes Element setzen und Kinder überspringen
    • XMLReader::open — URI angeben, die auf XML-Inhalt verweist, der geparst werden soll
    • XMLReader::read — Zeiger auf das nächste Element setzen
    • XMLReader::readInnerXml — Erhalte XML des aktuellen Knotens
    • XMLReader::readOuterXml — Liest XML des aktuellen Knotens, inklusive den Knoten selbst
    • XMLReader::readString — Liest den Inhalt des aktuellen Knotens als Zeichenkette
    • XMLReader::setParserProperty — Parser-Optionen setzen
    • XMLReader::setRelaxNGSchema — Dateiname oder URI des RelaxNG-Schema setzen
    • XMLReader::setRelaxNGSchemaSource — Zeichenkette setzen, die RelaxNG-Schemadaten enthält
    • XMLReader::setSchema — Validiert Dokument gegen XSD
    • XMLReader::XML — Zeichenkette setzen, deren Inhalt geparst werden soll

User Contributed Notes

There are no user contributed notes for this page.


Einführung

Die XMLReader-Erweiterung ist ein fortschreitender XML-Parser. Der Reader agiert wie ein Zeiger, der einen Datenstrom durchläuft und jeden vorbeikommenden Knoten der Reihe nach verarbeitet.

Encoding

Es ist wichtig zu beachten, dass die libxml intern die UTF-8 Kodierung verwendet und der gewonnene Inhalt daher immer in UTF-8 Kodierung vorliegt.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Der XMLReader wird mit dem PHP-Quellcode geliefert. Diese Erweiterung ist standardmäßig aktiviert. Sie kann bei der Kompilierung mit der folgenden Option ausgeschaltet werden: --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.


Die Klasse XMLReader

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

Einführung

Die Erweiterung XMLReader ist ein fortschreitender XML-Parser (XML-Pull-Parser). Der Reader agiert wie ein Zeiger, der einen Datenstrom durchläuft und jeden vorbeikommenden Knoten der Reihe nach verarbeitet.

Klassenbeschreibung

class XMLReader {
/* Konstanten */
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;
/* Eigenschaften */
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;
/* Methoden */
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
}

Eigenschaften

attributeCount

Die Anzahl der Attribute des aktuellen Knotens

baseURI

Der Basis-URI des Knotens

depth

Die Tiefe des Knotens im Baum, beginnend mit 0

hasAttributes

Zeigt an, ob der Knoten Attribute besitzt

hasValue

Zeigt an, ob der Knoten einen Text-Wert besitzt

isDefault

Zeigt an, ob das Attribute als Standard aus der DTD übernommen wurde

isEmptyElement

Zeigt an, ob der Knoten ein leeres Element-Tag ist

localName

Der lokale Name des Knotens

name

Der qualifizierte Name des Knotens

namespaceURI

Der URI des Namensraums, welcher mit dem Knoten assoziiert ist

nodeType

Der Typ des Knotens

prefix

Das Präfix, welches mit dem Namespaces des Knotens assoziiert wird

value

Der Text-Wert des Knotens

xmlLang

Der xml:lang-Bereich, in dem sich der Knoten befindet

Vordefinierte Konstanten

XMLReader-Knoten-Typen

XMLReader::NONE

Kein Typ

XMLReader::ELEMENT

Start-Element

XMLReader::ATTRIBUTE

Attribut-Knoten

XMLReader::TEXT

Text-Knoten

XMLReader::CDATA

CDATA-Knoten

XMLReader::ENTITY_REF

Entitätsreferenz-Knoten

XMLReader::ENTITY

Entitätsdeklarations-Knoten

XMLReader::PI

Verarbeitungsanweisungs-Knoten

XMLReader::COMMENT

Kommentar-Knoten

XMLReader::DOC

Dokument-Knoten

XMLReader::DOC_TYPE

Dokumenttyp-Knoten

XMLReader::DOC_FRAGMENT

Dokumentfragment-Knoten

XMLReader::NOTATION

Notationsknoten

XMLReader::WHITESPACE

Whitespace-Knoten

XMLReader::SIGNIFICANT_WHITESPACE

Significant-Whitespace-Knoten

XMLReader::END_ELEMENT

Schließendes Element

XMLReader::END_ENTITY

Entitätsende

XMLReader::XML_DECLARATION

XML-Deklarations-Knoten

XMLReader-Parser-Optionen

XMLReader::LOADDTD

DTD laden, aber nicht validieren

XMLReader::DEFAULTATTRS

DTD und Standardattribute laden, aber nicht validieren

XMLReader::VALIDATE

DTD laden und beim Parsen validieren

XMLReader::SUBST_ENTITIES

Entitäten ersetzen und Referenzen erweitern

Inhaltsverzeichnis

  • XMLReader::close — Beendet die XMLReader-Eingabe
  • XMLReader::expand — Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück
  • XMLReader::getAttribute — Liefert den Wert eines Attributes nach Namen
  • XMLReader::getAttributeNo — Gibt den Wert eines Attributes nach Position zurück
  • XMLReader::getAttributeNs — Gibt den Wert eines Attributes nach lokalem Namen und URI zurück
  • XMLReader::getParserProperty — Zeigt an, ob die angegebene Eigenschaft gesetzt wurde
  • XMLReader::isValid — Zeigt an, ob das geparste Dokument valide ist
  • XMLReader::lookupNamespace — Prüft, ob ein Namensbereich für einen Präfix vorhanden ist
  • XMLReader::moveToAttribute — Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader->moveToElement — Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToFirstAttribute — Zeiger auf erstes Attribut setzen
  • XMLReader::moveToNextAttribute — Zeiger auf nächstes Attribut setzen
  • XMLReader::next — Zeiger auf nächstes Element setzen und Kinder überspringen
  • XMLReader::open — URI angeben, die auf XML-Inhalt verweist, der geparst werden soll
  • XMLReader::read — Zeiger auf das nächste Element setzen
  • XMLReader::readInnerXml — Erhalte XML des aktuellen Knotens
  • XMLReader::readOuterXml — Liest XML des aktuellen Knotens, inklusive den Knoten selbst
  • XMLReader::readString — Liest den Inhalt des aktuellen Knotens als Zeichenkette
  • XMLReader::setParserProperty — Parser-Optionen setzen
  • XMLReader::setRelaxNGSchema — Dateiname oder URI des RelaxNG-Schema setzen
  • XMLReader::setRelaxNGSchemaSource — Zeichenkette setzen, die RelaxNG-Schemadaten enthält
  • XMLReader::setSchema — Validiert Dokument gegen XSD
  • XMLReader::XML — Zeichenkette setzen, deren Inhalt geparst werden soll

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>


Beendet die XMLReader-Eingabe

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Beendet die XMLReader-Eingabe

XMLReader::close

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

XMLReader::close — Beendet die XMLReader-Eingabe

Beschreibung

public XMLReader::close(): true

Beendet die Eingabe, die das XMLReader-Objekt gerade parst.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt immer true zurück.

Siehe auch

  • XMLReader::open() - URI angeben, die auf XML-Inhalt verweist, der geparst werden soll
  • XMLReader::xml() - Zeichenkette setzen, deren Inhalt geparst werden soll

User Contributed Notes

There are no user contributed notes for this page.


Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

XMLReader::expand

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

XMLReader::expand — Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

Beschreibung

public XMLReader::expand(?DOMNode $baseNode = null): DOMNode|false

Diese Methode kopiert den aktuellen Knoten und gibt ihn als entsprechendes DOM-Objekt zurück.

Parameter-Liste

baseNode

Ein DOMNode, der das DOMDocument-Ziel für das erzeugte DOM-Objekt definiert.

Rückgabewerte

Entsprechendes DOMNode oder false bei Fehlern.

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


Liefert den Wert eines Attributes nach Namen

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Liefert den Wert eines Attributes nach Namen

XMLReader::getAttribute

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

XMLReader::getAttribute — Liefert den Wert eines Attributes nach Namen

Beschreibung

public XMLReader::getAttribute(string $name): ?string

Der Wert des Attributes mit entsprechendem Namen oder null, wenn das Attribut nicht existiert oder der Cursor derzeit nicht über einem Elementknoten positioniert ist.

Parameter-Liste

name

Der Name des Attributes.

Rückgabewerte

Der Wert des Attributes oder null, wenn kein Attribut name im aktuellen Element gefunden wurde oder der Cursor derzeitig nicht über einem Elementknoten positioniert ist.

Changelog

Version | Beschreibung
8.0.0 | Diese Funktion gibt nicht mehr false zurück.

Siehe auch

  • XMLReader::getAttributeNo() - Gibt den Wert eines Attributes nach Position zurück
  • XMLReader::getAttributeNs() - Gibt den Wert eines Attributes nach lokalem Namen und URI zurück

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.


Gibt den Wert eines Attributes nach Position zurück

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Gibt den Wert eines Attributes nach Position zurück

XMLReader::getAttributeNo

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

XMLReader::getAttributeNo — Gibt den Wert eines Attributes nach Position zurück

Beschreibung

public XMLReader::getAttributeNo(int $index): ?string

Der Wert des Attributes an der angegebenen Position oder eine leere Zeichenkette, wenn das Attribut nicht existiert oder keinem Elementknoten zugeordnet ist.

Parameter-Liste

index

Position des Attributes.

Rückgabewerte

Der Wert des Attributes oder null, wenn kein Attribut an der Position index im aktuellen Element gefunden wurde.

Siehe auch

  • XMLReader::getAttribute() - Liefert den Wert eines Attributes nach Namen
  • XMLReader::getAttributeNs() - Gibt den Wert eines Attributes nach lokalem Namen und URI zurück

User Contributed Notes

There are no user contributed notes for this page.


Gibt den Wert eines Attributes nach lokalem Namen und URI zurück

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Gibt den Wert eines Attributes nach lokalem Namen und URI zurück

XMLReader::getAttributeNs

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

XMLReader::getAttributeNs — Gibt den Wert eines Attributes nach lokalem Namen und URI zurück

Beschreibung

public XMLReader::getAttributeNs(string $name, string $namespace): ?string

Gibt den Wert des Attributes mit entsprechendem Namen und Namensraum (URI) zurück oder eine leere Zeichenkette, wenn das Attribut nicht existiert oder der Cursor sich derzeitig nicht über einem Element befindet.

Parameter-Liste

name

Der lokale Name des Attributes.

namespace

Die URI des Namensraum.

Rückgabewerte

Der Wert des Attributes oder null, wenn kein Attribut mit den Parametern name und namespace im aktuellen Element gefunden wurde oder der Cursor sich derzeitig nicht über einem Element befindet.

Changelog

Version | Beschreibung
8.0.0 | This function can no longer return false.

Siehe auch

  • XMLReader::getAttribute() - Liefert den Wert eines Attributes nach Namen
  • XMLReader::getAttributeNo() - Gibt den Wert eines Attributes nach Position zurück

User Contributed Notes

There are no user contributed notes for this page.


Zeigt an, ob die angegebene Eigenschaft gesetzt wurde

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Zeigt an, ob die angegebene Eigenschaft gesetzt wurde

XMLReader::getParserProperty

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

XMLReader::getParserProperty — Zeigt an, ob die angegebene Eigenschaft gesetzt wurde

Beschreibung

public XMLReader::getParserProperty(int $property): bool

Zeigt an, ob die angegebene Eigenschaft gesetzt wurde.

Parameter-Liste

property

Eine der Parser-Optionskonstanten.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::setParserProperty() - Parser-Optionen setzen

User Contributed Notes

There are no user contributed notes for this page.


Zeigt an, ob das geparste Dokument valide ist

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Zeigt an, ob das geparste Dokument valide ist

XMLReader::isValid

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

XMLReader::isValid — Zeigt an, ob das geparste Dokument valide ist

Beschreibung

public XMLReader::isValid(): bool

Gibt einen booleschen Wert zurück, der angibt, ob das zu analysierende Dokument aktuell gemäß der DTD oder einem XML- oder RelaxNG-Schema gültig ist. Wenn es kein Schema gibt und die DTD-Validierungsoption nicht angegeben ist, gibt diese Methode false zurück.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt true zurück, wenn das Dokument gültig ist, oder false andernfalls.

Beispiele

Beispiel #1 Validierung von XML

<?php
$xml = XMLReader::open('test.xml');

// Die Option VALIDATE muss gesetzt werden, damit diese Methode
// ordnungsgemäß funktioniert
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Anmerkungen

Hinweis: Dies überprüft den aktuellen Knoten, nicht das gesamte Dokument.

Siehe auch

  • XMLReader::setParserProperty() - Parser-Optionen setzen
  • XMLReader::setRelaxNGSchema() - Dateiname oder URI des RelaxNG-Schema setzen
  • XMLReader::setRelaxNGSchemaSource() - Zeichenkette setzen, die RelaxNG-Schemadaten enthält
  • XMLReader::setSchema() - Validiert Dokument gegen 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).


Prüft, ob ein Namensbereich für einen Präfix vorhanden ist

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Prüft, ob ein Namensbereich für einen Präfix vorhanden ist

XMLReader::lookupNamespace

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

XMLReader::lookupNamespace — Prüft, ob ein Namensbereich für einen Präfix vorhanden ist

Beschreibung

public XMLReader::lookupNamespace(string $prefix): ?string

Prüfen, ob ein Namensbereich für den angegebenen Präfix vorhanden ist.

Parameter-Liste

prefix

Zeichenkette mit Präfix.

Rückgabewerte

Den Wert des Namensbereichs, oder null, falls es keinen Namensbereich gibt.

Changelog

Version | Beschreibung
8.0.0 | Diese Funktion gibt nicht mehr false zurück.

User Contributed Notes

There are no user contributed notes for this page.


Zeiger auf benanntes Attribut setzen

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Zeiger auf benanntes Attribut setzen

XMLReader::moveToAttribute

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

XMLReader::moveToAttribute — Zeiger auf benanntes Attribut setzen

Beschreibung

public XMLReader::moveToAttribute(string $name): bool

Zeiger auf benanntes Attribut setzen.

Parameter-Liste

name

Name des Attributes.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Zeiger auf erstes Attribut setzen

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

Beschreibung

public XMLReader::moveToAttributeNo(int $index): bool

Positions cursor on attribute based on its position.

Parameter-Liste

index

The position of the attribute.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Zeiger auf erstes Attribut setzen

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

Beschreibung

public XMLReader::moveToAttributeNs(string $name, string $namespace): bool

Positions cursor on the named attribute in specified namespace.

Parameter-Liste

name

The local name.

namespace

The namespace URI.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Zeiger auf erstes Attribut setzen

User Contributed Notes

There are no user contributed notes for this page.


Zeiger positionieren auf das Elternelement des aktuellen Attributes

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Zeiger positionieren auf das Elternelement des aktuellen Attributes

XMLReader->moveToElement

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

XMLReader->moveToElement — Zeiger positionieren auf das Elternelement des aktuellen Attributes

Beschreibung

public XMLReader::moveToElement(): bool

Setzt Zeiger auf das Elternelement des aktuellen Attributes.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück und false, wenn es fehlgeschlagen ist oder die Methode aufgerufen wird, wenn der Zeiger nicht auf ein Attribut zeigt.

Siehe auch

  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Zeiger auf erstes Attribut setzen

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.


Zeiger auf erstes Attribut setzen

  • « XMLReader->moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Zeiger auf erstes Attribut setzen

XMLReader::moveToFirstAttribute

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

XMLReader::moveToFirstAttribute — Zeiger auf erstes Attribut setzen

Beschreibung

public XMLReader::moveToFirstAttribute(): bool

Setzt den Zeiger auf das erste Attribut im Element.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Zeiger auf nächstes Attribut setzen

User Contributed Notes

There are no user contributed notes for this page.


Zeiger auf nächstes Attribut setzen

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Zeiger auf nächstes Attribut setzen

XMLReader::moveToNextAttribute

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

XMLReader::moveToNextAttribute — Zeiger auf nächstes Attribut setzen

Beschreibung

public XMLReader::moveToNextAttribute(): bool

Setzt den Zeiger auf das nächste Attribut, wenn er auf ein Attribut verweist oder auf's erste Attribut, wenn er auf ein Element verweist.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Zeiger auf erstes Attribut setzen

User Contributed Notes

There are no user contributed notes for this page.


Zeiger auf nächstes Element setzen und Kinder überspringen

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Zeiger auf nächstes Element setzen und Kinder überspringen

XMLReader::next

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

XMLReader::next — Zeiger auf nächstes Element setzen und Kinder überspringen

Beschreibung

public XMLReader::next(?string $name = null): bool

Setzt den Zeiger auf das nächste Element und überspringt dabei Kindelemente. Falls es kein solches Element gibt, wird der Zeiger ans Ende des Dokuments gesetzt.

Parameter-Liste

name

Name des nächsten Elements.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | name ist jetzt ein Nullable-Typ.

Siehe auch

  • XMLReader::moveToNextAttribute() - Zeiger auf nächstes Attribut setzen
  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen

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


URI angeben, die auf XML-Inhalt verweist, der geparst werden soll

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • URI angeben, die auf XML-Inhalt verweist, der geparst werden soll

XMLReader::open

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

XMLReader::open — URI angeben, die auf XML-Inhalt verweist, der geparst werden soll

Beschreibung

public static XMLReader::open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader

URI angeben, die auf XML-Inhalt verweist, der geparst werden soll.

Parameter-Liste

uri

URI die auf den XML-Inhalt verweist.

encoding

Dokumentkodierung oder null.

flags

Bitmaske bestehend aus LIBXML_*-Konstanten.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben. Wenn die Methode statisch aufgerufen wird, wird eine XMLReader-Instanz zurückgegeben oder im Fehlerfall false.

Fehler/Exceptions

Diese Methode kann statisch aufgerufen werden, gibt aber in diesem Fall vor PHP 8.0.0 einen E_DEPRECATED-Fehler aus.

Changelog

Version | Beschreibung
8.0.0 | XMLReader::open() ist jetzt als statische Methode deklariert, kann aber weiterhin auf einer XMLReader-Instanz aufgerufen werden.

Siehe auch

  • XMLReader::xml() - Zeichenkette setzen, deren Inhalt geparst werden soll
  • XMLReader::close() - Beendet die XMLReader-Eingabe

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.


Zeiger auf das nächste Element setzen

  • « XMLReader::open
  • XMLReader::readInnerXml »
  • PHP Manual
  • XMLReader
  • Zeiger auf das nächste Element setzen

XMLReader::read

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

XMLReader::read — Zeiger auf das nächste Element setzen

Beschreibung

public XMLReader::read(): bool

Zeiger auf das nächste Element im Dokument setzen.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::moveToElement() - Zeiger positionieren auf das Elternelement des aktuellen Attributes
  • XMLReader::moveToAttribute() - Zeiger auf benanntes Attribut setzen
  • XMLReader::next() - Zeiger auf nächstes Element setzen und Kinder überspringen

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.


Erhalte XML des aktuellen Knotens

  • « XMLReader::read
  • XMLReader::readOuterXml »
  • PHP Manual
  • XMLReader
  • Erhalte XML des aktuellen Knotens

XMLReader::readInnerXml

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

XMLReader::readInnerXml — Erhalte XML des aktuellen Knotens

Beschreibung

public XMLReader::readInnerXml(): string

Liest den Inhalt des aktuellen Knoten, inklusive der Kind-Knoten und Markup.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt Inhalt des aktuellen Knotens als Zeichenkette zurück; im Fehlerfall eine leere Zeichenkette.

Anmerkungen

Achtung

Diese Funktion ist nur verfügbar, wenn PHP mit libxml 20620 oder später kompiliert wurde.

Siehe auch

  • XMLReader::readString() - Liest den Inhalt des aktuellen Knotens als Zeichenkette
  • XMLReader::readOuterXml() - Liest XML des aktuellen Knotens, inklusive den Knoten selbst
  • XMLReader::expand() - Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

User Contributed Notes

There are no user contributed notes for this page.


Liest XML des aktuellen Knotens, inklusive den Knoten selbst

  • « XMLReader::readInnerXml
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Liest XML des aktuellen Knotens, inklusive den Knoten selbst

XMLReader::readOuterXml

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

XMLReader::readOuterXml — Liest XML des aktuellen Knotens, inklusive den Knoten selbst

Beschreibung

public XMLReader::readOuterXml(): string

Liest den Inhalt des aktuellen Knotens, inklusive den Knoten selbst.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt Inhalt des aktuellen Knotens inklusive dem Knoten selbst als Zeichenkette zurück; im Fehlerfall eine leere Zeichenkette.

Anmerkungen

Achtung

Diese Funktion ist nur verfügbar, wenn PHP mit libxml 20620 oder später kompiliert wurde.

Siehe auch

  • XMLReader::readString() - Liest den Inhalt des aktuellen Knotens als Zeichenkette
  • XMLReader::readInnerXml() - Erhalte XML des aktuellen Knotens
  • XMLReader::expand() - Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

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.


Liest den Inhalt des aktuellen Knotens als Zeichenkette

  • « XMLReader::readOuterXml
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Liest den Inhalt des aktuellen Knotens als Zeichenkette

XMLReader::readString

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

XMLReader::readString — Liest den Inhalt des aktuellen Knotens als Zeichenkette

Beschreibung

public XMLReader::readString(): string

Liest den Inhalt des aktuellen Knotens als Zeichenkette.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt den Inhalt des aktuellen Knotens als Zeichenkette zurück; im Fehlerfall eine leere Zeichenkette.

Anmerkungen

Achtung

Diese Funktion ist nur verfügbar, wenn PHP mit libxml 20620 oder später kompiliert wurde.

Siehe auch

  • XMLReader::readOuterXml() - Liest XML des aktuellen Knotens, inklusive den Knoten selbst
  • XMLReader::readInnerXml() - Erhalte XML des aktuellen Knotens
  • XMLReader::expand() - Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück

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>


Parser-Optionen setzen

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Parser-Optionen setzen

XMLReader::setParserProperty

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

XMLReader::setParserProperty — Parser-Optionen setzen

Beschreibung

public XMLReader::setParserProperty(int $property, bool $value): bool

Setzen von Optionen für den Parser. Die Optionen müssen definiert werden nachdem XMLReader::open() oder XMLReader::xml() verwendet werden und bevor der erste XMLReader::read() Aufruf stattfindet.

Parameter-Liste

property

Eine der Parser-Optionskonstanten.

value

Wenn die Option auf true gesetzt, wird sie aktiviert, sonst deaktiviert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

User Contributed Notes

There are no user contributed notes for this page.


Dateiname oder URI des RelaxNG-Schema setzen

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Dateiname oder URI des RelaxNG-Schema setzen

XMLReader::setRelaxNGSchema

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

XMLReader::setRelaxNGSchema — Dateiname oder URI des RelaxNG-Schema setzen

Beschreibung

public XMLReader::setRelaxNGSchema(?string $filename): bool

Dateiname oder URI des RelaxNG-Schemas setzen, das zur Validierung verwendet werden soll.

Parameter-Liste

filename

Dateiname oder URI des RelaxNG-Schemas.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::setRelaxNGSchemaSource() - Zeichenkette setzen, die RelaxNG-Schemadaten enthält
  • XMLReader::setSchema() - Validiert Dokument gegen XSD
  • XMLReader::isValid() - Zeigt an, ob das geparste Dokument valide ist

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


Zeichenkette setzen, die RelaxNG-Schemadaten enthält

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Zeichenkette setzen, die RelaxNG-Schemadaten enthält

XMLReader::setRelaxNGSchemaSource

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

XMLReader::setRelaxNGSchemaSource — Zeichenkette setzen, die RelaxNG-Schemadaten enthält

Beschreibung

public XMLReader::setRelaxNGSchemaSource(?string $source): bool

Zeichenkette setzen, die RelaxNG-Schemadaten enthält, gegen die validiert werden soll.

Parameter-Liste

source

Zeichenkette die RelaxNG-Schemadaten enthält.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XMLReader::setRelaxNGSchema() - Dateiname oder URI des RelaxNG-Schema setzen
  • XMLReader::setSchema() - Validiert Dokument gegen XSD
  • XMLReader::isValid() - Zeigt an, ob das geparste Dokument valide ist

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


Validiert Dokument gegen XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Validiert Dokument gegen XSD

XMLReader::setSchema

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

XMLReader::setSchema — Validiert Dokument gegen XSD

Beschreibung

public XMLReader::setSchema(?string $filename): bool

Nutzen Sie W3C-XSD-Schema um das Dokument während der Verarbeitung zu validieren. Die Aktivierung ist nur vor dem ersten Read() Aufruf möglich.

Parameter-Liste

filename

Der Dateiname des XSD-Schema.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

Gibt E_WARNING aus, falls libxml ohne Schema Unterstützung kompiliert wurde, das Schema Fehler enthält oder wenn XMLReader::read() schon aufgerufen wurde.

Anmerkungen

Achtung

Diese Funktion ist nur verfügbar, wenn PHP mit libxml 20620 oder später kompiliert wurde.

Siehe auch

  • XMLReader::setRelaxNGSchema() - Dateiname oder URI des RelaxNG-Schema setzen
  • XMLReader::setRelaxNGSchemaSource() - Zeichenkette setzen, die RelaxNG-Schemadaten enthält
  • XMLReader::isValid() - Zeigt an, ob das geparste Dokument valide ist

User Contributed Notes

There are no user contributed notes for this page.


Zeichenkette setzen, deren Inhalt geparst werden soll

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Zeichenkette setzen, deren Inhalt geparst werden soll

XMLReader::XML

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

XMLReader::XML — Zeichenkette setzen, deren Inhalt geparst werden soll

Beschreibung

public static XMLReader::XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader

Zeichenkette mit XML-Inhalt setzen, der geparst werden soll.

Parameter-Liste

source

Zeichenkette mit XML-Inhalt, der geparst werden soll.

encoding

Dokumentkodierung oder null.

flags

Bitmaske bestehend aus LIBXML_*-Konstanten.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben. Wenn die Methode statisch aufgerufen wird, wird eine XMLReader-Instanz zurückgegeben oder im Fehlerfall false.

Fehler/Exceptions

Diese Methode kann statisch aufgerufen werden, gibt aber in diesem Fall vor PHP 8.0.0 einen E_DEPRECATED-Fehler aus.

Changelog

Version | Beschreibung
8.0.0 | XMLReader::XML() ist jetzt als statische Methode deklariert, kann aber weiterhin auf einer XMLReader-Instanz aufgerufen werden.

Siehe auch

  • XMLReader::open() - URI angeben, die auf XML-Inhalt verweist, der geparst werden soll
  • XMLReader::close() - Beendet die XMLReader-Eingabe

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Beispiele
    • Creating a simple XML document
    • Working with XML namespaces
    • Working with the OO API
  • XMLWriter — The XMLWriter class
    • XMLWriter::endAttribute — Attribute beenden
    • XMLWriter::endCdata — Beendet CDATA-Block
    • XMLWriter::endComment — Beendet Kommentar
    • XMLWriter::endDocument — Beendet Dokument
    • XMLWriter::endDtd — Beendet DTD
    • XMLWriter::endDtdAttlist — Beendet DTD-Attributliste
    • XMLWriter::endDtdElement — Beendet DTD-Element
    • XMLWriter::endDtdEntity — Beendet DTD-Entität
    • XMLWriter::endElement — Beendet Element
    • XMLWriter::endPi — Beendet Verarbeitungsvorschrift
    • XMLWriter::flush — Puffer schreiben
    • XMLWriter::fullEndElement — Beendet Element
    • XMLWriter::openMemory — Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt
    • XMLWriter::openUri — Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet
    • XMLWriter::outputMemory — Gibt Puffer zurück
    • XMLWriter::setIndent — Einrückung ein-/ausschalten
    • XMLWriter::setIndentString — Setzt Zeichenkette, die zur Einrückung verwendet wird
    • XMLWriter::startAttribute — Attribut beginnen
    • XMLWriter::startAttributeNs — Namensraum-Attribut beginnen
    • XMLWriter::startCdata — CDATA-Block beginnen
    • XMLWriter::startComment — Kommentar beginnen
    • XMLWriter::startDocument — Dokument beginnen
    • XMLWriter::startDtd — DTD beginnen
    • XMLWriter::startDtdAttlist — DTD-Attributliste beginnen
    • XMLWriter::startDtdElement — DTD-Element beginnen
    • XMLWriter::startDtdEntity — DTD-Entität beginnen
    • XMLWriter::startElement — Element beginnen
    • XMLWriter::startElementNs — Element mit Namensraum beginnen
    • XMLWriter::startPi — Verarbeitungsvorschrift beginnen
    • XMLWriter::text — Text schreiben
    • XMLWriter::writeAttribute — Komplettes Attribut schreiben
    • XMLWriter::writeAttributeNs — Komplettes Attribute mit Namensraum schreiben
    • XMLWriter::writeCdata — Kompletten CDATA-Block schreiben
    • XMLWriter::writeComment — Kompletten Kommentar schreiben
    • XMLWriter::writeDtd — Komplettes DTD-Tag schreiben
    • XMLWriter::writeDtdAttlist — Komplette DTD-Attributliste schreiben
    • XMLWriter::writeDtdElement — Komplettes DTD-Element schreiben
    • XMLWriter::writeDtdEntity — Komplette DTD-Entität schreiben
    • XMLWriter::writeElement — Komplettes Element schreiben
    • XMLWriter::writeElementNs — Komplettes Element mit Namensraum schreiben
    • XMLWriter::writePi — Komplette Verarbeitungsvorschrift-Tag schreiben
    • XMLWriter::writeRaw — Reines XML schreiben

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!


Einführung

Die XMLWriter-Erweiterung ist ein Wrapper für die libxml xmlWriter-API.

Diese Erweiterung bietet einen nicht zwischenspeichernden, fortschreitenden Schreiber zum Erzeugen von Datenströmen oder Dateien mit XML-Inhalten.

Diese Erweiterung kann sowohl objektorientier als auch prozedural verwendet werden. Jede dokumentierte Methode beschreibt auch den entsprechenden prozeduralen Aufruf.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Der XMLWriter wird mit dem PHP-Quellcode geliefert. Diese Erweiterung ist standardmäßig aktiviert. Sie kann bei der Kompilierung mit der folgenden Option ausgeschaltet werden: --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


Ressource-Typen

In der prozeduralen Version der XMLWriter-Erweiterung wird nur eine Ressource verwendet. Diese wird von xmlwriter_open_memory() oder xmlwriter_open_uri() zurückgegeben.

User Contributed Notes

There are no user contributed notes for this page.


Beispiele

Inhaltsverzeichnis

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Einführung

Klassenbeschreibung

class XMLWriter {
/* Methoden */
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 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
}

Inhaltsverzeichnis

  • XMLWriter::endAttribute — Attribute beenden
  • XMLWriter::endCdata — Beendet CDATA-Block
  • XMLWriter::endComment — Beendet Kommentar
  • XMLWriter::endDocument — Beendet Dokument
  • XMLWriter::endDtd — Beendet DTD
  • XMLWriter::endDtdAttlist — Beendet DTD-Attributliste
  • XMLWriter::endDtdElement — Beendet DTD-Element
  • XMLWriter::endDtdEntity — Beendet DTD-Entität
  • XMLWriter::endElement — Beendet Element
  • XMLWriter::endPi — Beendet Verarbeitungsvorschrift
  • XMLWriter::flush — Puffer schreiben
  • XMLWriter::fullEndElement — Beendet Element
  • XMLWriter::openMemory — Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt
  • XMLWriter::openUri — Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet
  • XMLWriter::outputMemory — Gibt Puffer zurück
  • XMLWriter::setIndent — Einrückung ein-/ausschalten
  • XMLWriter::setIndentString — Setzt Zeichenkette, die zur Einrückung verwendet wird
  • XMLWriter::startAttribute — Attribut beginnen
  • XMLWriter::startAttributeNs — Namensraum-Attribut beginnen
  • XMLWriter::startCdata — CDATA-Block beginnen
  • XMLWriter::startComment — Kommentar beginnen
  • XMLWriter::startDocument — Dokument beginnen
  • XMLWriter::startDtd — DTD beginnen
  • XMLWriter::startDtdAttlist — DTD-Attributliste beginnen
  • XMLWriter::startDtdElement — DTD-Element beginnen
  • XMLWriter::startDtdEntity — DTD-Entität beginnen
  • XMLWriter::startElement — Element beginnen
  • XMLWriter::startElementNs — Element mit Namensraum beginnen
  • XMLWriter::startPi — Verarbeitungsvorschrift beginnen
  • XMLWriter::text — Text schreiben
  • XMLWriter::writeAttribute — Komplettes Attribut schreiben
  • XMLWriter::writeAttributeNs — Komplettes Attribute mit Namensraum schreiben
  • XMLWriter::writeCdata — Kompletten CDATA-Block schreiben
  • XMLWriter::writeComment — Kompletten Kommentar schreiben
  • XMLWriter::writeDtd — Komplettes DTD-Tag schreiben
  • XMLWriter::writeDtdAttlist — Komplette DTD-Attributliste schreiben
  • XMLWriter::writeDtdElement — Komplettes DTD-Element schreiben
  • XMLWriter::writeDtdEntity — Komplette DTD-Entität schreiben
  • XMLWriter::writeElement — Komplettes Element schreiben
  • XMLWriter::writeElementNs — Komplettes Element mit Namensraum schreiben
  • XMLWriter::writePi — Komplette Verarbeitungsvorschrift-Tag schreiben
  • XMLWriter::writeRaw — Reines XML schreiben

User Contributed Notes

There are no user contributed notes for this page.


Attribute beenden

  • « XMLWriter
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter
  • Attribute beenden

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — Attribute beenden

Beschreibung

Objektorientierter Stil

public XMLWriter::endAttribute(): bool

Prozeduraler Stil

xmlwriter_end_attribute(XMLWriter $writer): bool

Beendet das aktuelle Attribut.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startAttribute() - Attribut beginnen
  • XMLWriter::startAttributeNs() - Namensraum-Attribut beginnen
  • XMLWriter::writeAttribute() - Komplettes Attribut schreiben
  • XMLWriter::writeAttributeNs() - Komplettes Attribute mit Namensraum schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet CDATA-Block

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • Beendet CDATA-Block

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — Beendet CDATA-Block

Beschreibung

Objektorientierter Stil

public XMLWriter::endCdata(): bool

Prozeduraler Stil

xmlwriter_end_cdata(XMLWriter $writer): bool

Beendet den aktuellen CDATA-Block.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startCdata() - CDATA-Block beginnen
  • XMLWriter::writeCdata() - Kompletten CDATA-Block schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet Kommentar

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Beendet Kommentar

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Beendet Kommentar

Beschreibung

Objektorientierter Stil

public XMLWriter::endComment(): bool

Prozeduraler Stil

xmlwriter_end_comment(XMLWriter $writer): bool

Beendet aktuellen Kommentar.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startComment() - Kommentar beginnen
  • XMLWriter::writeComment() - Kompletten Kommentar schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet Dokument

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • Beendet Dokument

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — Beendet Dokument

Beschreibung

Objektorientierter Stil

public XMLWriter::endDocument(): bool

Prozeduraler Stil

xmlwriter_end_document(XMLWriter $writer): bool

Beendet das aktuelle Dokument.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDocument() - Dokument beginnen

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


Beendet DTD

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Beendet 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 — Beendet DTD

Beschreibung

Objektorientierter Stil

public XMLWriter::endDtd(): bool

Prozeduraler Stil

xmlwriter_end_dtd(XMLWriter $writer): bool

Beendet die DTD des Dokuments.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtd() - DTD beginnen
  • XMLWriter::writeDtd() - Komplettes DTD-Tag schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet DTD-Attributliste

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • Beendet DTD-Attributliste

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 — Beendet DTD-Attributliste

Beschreibung

Objektorientierter Stil

public XMLWriter::endDtdAttlist(): bool

Prozeduraler Stil

xmlwriter_end_dtd_attlist(XMLWriter $writer): bool

Beendet die aktuelle DTD-Attributlist.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtdAttlist() - DTD-Attributliste beginnen
  • XMLWriter::writeDtdAttlist() - Komplette DTD-Attributliste schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet DTD-Element

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • Beendet 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 — Beendet DTD-Element

Beschreibung

Objektorientierter Stil

public XMLWriter::endDtdElement(): bool

Prozeduraler Stil

xmlwriter_end_dtd_element(XMLWriter $writer): bool

Beendet das aktuelle DTD-Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtdElement() - DTD-Element beginnen
  • XMLWriter::writeDtdElement() - Komplettes DTD-Element schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet DTD-Entität

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • Beendet DTD-Entität

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 — Beendet DTD-Entität

Beschreibung

Objektorientierter Stil

public XMLWriter::endDtdEntity(): bool

Prozeduraler Stil

xmlwriter_end_dtd_entity(XMLWriter $writer): bool

Beendet die aktuelle DTD-Entität.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtdEntity() - DTD-Entität beginnen
  • XMLWriter::writeDtdEntity() - Komplette DTD-Entität schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet Element

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • Beendet 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 — Beendet Element

Beschreibung

Objektorientierter Stil

public XMLWriter::endElement(): bool

Prozeduraler Stil

xmlwriter_end_element(XMLWriter $writer): bool

Beendet das aktuelle Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startElement() - Element beginnen
  • XMLWriter::writeElement() - Komplettes Element schreiben

User Contributed Notes

There are no user contributed notes for this page.


Beendet Verarbeitungsvorschrift

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • Beendet Verarbeitungsvorschrift

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — Beendet Verarbeitungsvorschrift

Beschreibung

Objektorientierter Stil

public XMLWriter::endPi(): bool

Prozeduraler Stil

xmlwriter_end_pi(XMLWriter $writer): bool

Beendet die aktuelle Verarbeitungsvorschrift.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startPi() - Verarbeitungsvorschrift beginnen
  • XMLWriter::writePi() - Komplette Verarbeitungsvorschrift-Tag schreiben

User Contributed Notes

There are no user contributed notes for this page.


Puffer schreiben

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Puffer schreiben

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Puffer schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::flush(bool $empty = true): string|int

Prozeduraler Stil

xmlwriter_flush(XMLWriter $writer, bool $empty = true): string|int

Schreibt den aktuellen Puffer.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

empty

Ob der Puffer geleert werden soll oder nicht. Standard ist true.

Rückgabewerte

Wenn der XMLWriter den Speicher verwendet, wird das erzeugte XML zurückgegeben, sonst, wenn er einen URI verwendet, werden die Daten geschrieben und die Anzahl der geschriebenen Bytes zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.
8.0.0 | Diese Funktion kann nicht länger false zurückgeben.

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


Beendet Element

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • Beendet 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 — Beendet Element

Beschreibung

Objektorientierter Stil

public XMLWriter::fullEndElement(): bool

Prozeduraler Stil

xmlwriter_full_end_element(XMLWriter $writer): bool

Beendet das aktuelle XML-Element. Schreibt einen schließenden Tag, auch, wenn das Element leer ist.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endElement() - Beendet Element

User Contributed Notes

There are no user contributed notes for this page.


Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt

Beschreibung

Objektorientierter Stil

public XMLWriter::openMemory(): bool

Prozeduraler Stil

xmlwriter_open_memory(): XMLWriter|false

Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt.

Parameter-Liste

Rückgabewerte

Objektorientierter Stil: Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Prozeduraler Stil: Gibt bei Erfolg ein neues XMLWriter Exemplar zurück, die später für XMLWriter-Funktionen verwendet werden kann. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | Diese Funktion gibt nun bei Erfolgt ein XMLWriter Exemplar zurück. Zuvor wurde in diesem Fall eine Ressource zurückgegeben.

Siehe auch

  • XMLWriter::openUri() - Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet

User Contributed Notes

There are no user contributed notes for this page.


Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet

Beschreibung

Objektorientierter Stil

public XMLWriter::openUri(string $uri): bool

Prozeduraler Stil

xmlwriter_open_uri(string $uri): XMLWriter|false

Erzeugt einen neuen XMLWriter, der ein uri zum Erzeugen verwendet.

Parameter-Liste

uri

Der Ressource-URI, der zur Ausgabe verwendet wird.

Rückgabewerte

Objektorientierter Stil: Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben..

Prozeduraler Stil: Gibt ein neues XMLWriter Exemplar zurück, die bei Erfolg für die späteren Funktionsaufrufe verwendet werden kann. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | Diese Funktion gibt nun bei Erfolgt ein XMLWriter Exemplar zurück. Zuvor wurde in diesem Fall eine Ressource zurückgegeben.

Beispiele

Beispiel #1 Direkte Ausgabe von XML

Es ist möglich XML unter Verwendung des php://output Stream wrappers direkt auszugeben.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

Anmerkungen

Hinweis:

Unter Windows sind Dateien, die durch diese Funktion geöffnet wurden, gesperrt bis der Writer freigegeben wird.

Siehe auch

  • XMLWriter::openMemory() - Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt

User Contributed Notes

There are no user contributed notes for this page.


Gibt Puffer zurück

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Gibt Puffer zurück

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Gibt Puffer zurück

Beschreibung

Objektorientierter Stil

public XMLWriter::outputMemory(bool $flush = true): string

Prozeduraler Stil

xmlwriter_output_memory(XMLWriter $writer, bool $flush = true): string

Gibt den aktuellen Puffer-Inhalt zurück.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

flush

Ob der Puffer geleert werden soll oder nicht. Standard ist true.

Rückgabewerte

Gibt den aktuellen Puffer-Inhalt als Zeichenkette zurück.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::flush() - Puffer schreiben

User Contributed Notes

There are no user contributed notes for this page.


Einrückung ein-/ausschalten

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Einrückung ein-/ausschalten

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Einrückung ein-/ausschalten

Beschreibung

Objektorientierter Stil

public XMLWriter::setIndent(bool $enable): bool

Prozeduraler Stil

xmlwriter_set_indent(XMLWriter $writer, bool $enable): bool

Einrückung ein- oder ausschalten.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

enable

Ob Einrückungen verwendet werden sollen. Standard ist false.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Beispiele

Beispiel #1 XMLWriter::setIndent() und gemischter Inhalt

Das Aktivieren der Einrückung ist für gemischten Inhalt nicht geeignet, da der Einrückungsstring ebenfalls vor Inline-Elementen eingefügt wird.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

Anmerkungen

Hinweis:

Die Einrückung wird zurückgesetzt, wenn ein XMLWriter geöffnet wird.

Siehe auch

  • XMLWriter::setIndentString() - Setzt Zeichenkette, die zur Einrückung verwendet wird

User Contributed Notes

info at ensostudio dot ru 04-Apr-2021 01:04
NOTE: $enable can be integer as in example, or boolean.


Setzt Zeichenkette, die zur Einrückung verwendet wird

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Setzt Zeichenkette, die zur Einrückung verwendet wird

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 — Setzt Zeichenkette, die zur Einrückung verwendet wird

Beschreibung

Objektorientierter Stil

public XMLWriter::setIndentString(string $indentation): bool

Prozeduraler Stil

xmlwriter_set_indent_string(XMLWriter $writer, string $indentation): bool

Setzt eine Zeichenkette, die zum Einrücken von Elementen und Attributen im erzeugten XML verwendet wird.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

indentation

Einrückung.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Anmerkungen

Hinweis:

Die Einrückung wird zurückgesetzt, wenn ein XMLWriter geöffnet wird.

Siehe auch

  • XMLWriter::setIndent() - Einrückung ein-/ausschalten

User Contributed Notes

There are no user contributed notes for this page.


Attribut beginnen

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Attribut beginnen

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Attribut beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startAttribute(string $name): bool

Prozeduraler Stil

xmlwriter_start_attribute(XMLWriter $writer, string $name): bool

Beginnt ein neues Attribut.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Attributname.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Beispiele

Beispiel #1 Grundsätzliche XMLWriter::startAttribute() Verwendung

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

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

Siehe auch

  • XMLWriter::startAttributeNs() - Namensraum-Attribut beginnen
  • XMLWriter::endAttribute() - Attribute beenden
  • XMLWriter::writeAttribute() - Komplettes Attribut schreiben
  • XMLWriter::writeAttributeNs() - Komplettes Attribute mit Namensraum schreiben

User Contributed Notes

There are no user contributed notes for this page.


Namensraum-Attribut beginnen

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Namensraum-Attribut beginnen

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 — Namensraum-Attribut beginnen

Beschreibung

>Objektorientierter Stil

public XMLWriter::startAttributeNs(?string $prefix, string $name, ?string $namespace): bool

Prozeduraler Stil

xmlwriter_start_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Beginnt ein neues Attribut im definierten Namensraum.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

prefix

Namensraum-Präfix.

name

Attributname.

namespace

Namensraum-URI. Ist uri null, wird die Namensraumdeklaration ausgelassen.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.
8.0.0 | prefix ist nun nullbar.

Siehe auch

  • XMLWriter::startAttribute() - Attribut beginnen
  • XMLWriter::endAttribute() - Attribute beenden
  • XMLWriter::writeAttribute() - Komplettes Attribut schreiben
  • XMLWriter::writeAttributeNs() - Komplettes Attribute mit Namensraum schreiben

User Contributed Notes

There are no user contributed notes for this page.


CDATA-Block beginnen

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • CDATA-Block beginnen

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — CDATA-Block beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startCdata(): bool

Prozeduraler Stil

xmlwriter_start_cdata(XMLWriter $writer): bool

Beginnt einen CDATA-Block.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endCdata() - Beendet CDATA-Block
  • XMLWriter::writeCdata() - Kompletten CDATA-Block schreiben

User Contributed Notes

There are no user contributed notes for this page.


Kommentar beginnen

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Kommentar beginnen

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Kommentar beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startComment(): bool

Prozeduraler Stil

xmlwriter_start_comment(XMLWriter $writer): bool

Beginnt ein Kommentar.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endComment() - Beendet Kommentar
  • XMLWriter::writeComment() - Kompletten Kommentar schreiben

User Contributed Notes

There are no user contributed notes for this page.


Dokument beginnen

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Dokument beginnen

XMLWriter::startDocument

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument — Dokument beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool

Prozeduraler Stil

xmlwriter_start_document(
XMLWriter $writer,
?string $version = "1.0",
?string $encoding = null,
?string $standalone = null
): bool

Beginnt ein neues Dokument.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

version

Versionsnummer des Dokuments als Teil der XML-Deklaration.

encoding

Kodierung des Dokuments als Teil der XML-Deklaration.

standalone

yes oder no. Standardmäßig null.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endDocument() - Beendet Dokument

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


DTD beginnen

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • DTD beginnen

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — DTD beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool

Prozeduraler Stil

xmlwriter_start_dtd(
XMLWriter $writer,
string $qualifiedName,
?string $publicId = null,
?string $systemId = null
): bool

Beginnt DTD.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

qualifiedName

Qualifizierter Name des zu erstellenden Dokumententyps.

publicId

Public Identifier für PUBLIC.

systemId

Public Identifier für SYSTEM.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endDtd() - Beendet DTD
  • XMLWriter::writeDtd() - Komplettes DTD-Tag schreiben

User Contributed Notes

There are no user contributed notes for this page.


DTD-Attributliste beginnen

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • DTD-Attributliste beginnen

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 — DTD-Attributliste beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startDtdAttlist(string $name): bool

Prozeduraler Stil

xmlwriter_start_dtd_attlist(XMLWriter $writer, string $name): bool

Beginnt eine DTD-Attributliste.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name der Attributliste.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endDtdAttlist() - Beendet DTD-Attributliste
  • XMLWriter::writeDtdAttlist() - Komplette DTD-Attributliste schreiben

User Contributed Notes

There are no user contributed notes for this page.


DTD-Element beginnen

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • DTD-Element beginnen

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 — DTD-Element beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startDtdElement(string $qualifiedName): bool

Prozeduraler Stil

xmlwriter_start_dtd_element(XMLWriter $writer, string $qualifiedName): bool

Beginnt ein DTD-Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

qualifiedName

Qualifizierter Name des zu erstellenden Dokumententyps.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endDtdElement() - Beendet DTD-Element
  • XMLWriter::writeDtdElement() - Komplettes DTD-Element schreiben

User Contributed Notes

There are no user contributed notes for this page.


DTD-Entität beginnen

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • DTD-Entität beginnen

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 — DTD-Entität beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startDtdEntity(string $name, bool $isParam): bool

Prozeduraler Stil

xmlwriter_start_dtd_entity(XMLWriter $writer, string $name, bool $isParam): bool

Beginnt eine DTD-Entität.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name der Entität.

isParam

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endDtdEntity() - Beendet DTD-Entität
  • XMLWriter::writeDtdEntity() - Komplette DTD-Entität schreiben

User Contributed Notes

There are no user contributed notes for this page.


Element beginnen

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Element beginnen

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Element beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startElement(string $name): bool

Prozeduraler Stil

xmlwriter_start_element(XMLWriter $writer, string $name): bool

Beginnt ein Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Elementname.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endElement() - Beendet Element
  • XMLWriter::writeElement() - Komplettes Element schreiben

User Contributed Notes

There are no user contributed notes for this page.


Element mit Namensraum beginnen

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Element mit Namensraum beginnen

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 — Element mit Namensraum beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startElementNs(?string $prefix, string $name, ?string $namespace): bool

Prozeduraler Stil

xmlwriter_start_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Beginnt ein Element im angegebenen Namensraum.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

prefix

Präfix des Namensraum. Ist prefix null, wird der Namensraum ausgelassen.

name

Elementname.

namespace

URI des Namensraum. Ist namespace null, wird die Namensraumdeklaration ausgelassen.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endElement() - Beendet Element
  • XMLWriter::writeElementNs() - Komplettes Element mit Namensraum schreiben

User Contributed Notes

There are no user contributed notes for this page.


Verarbeitungsvorschrift beginnen

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Verarbeitungsvorschrift beginnen

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Verarbeitungsvorschrift beginnen

Beschreibung

Objektorientierter Stil

public XMLWriter::startPi(string $target): bool

Prozeduraler Stil

xmlwriter_start_pi(XMLWriter $writer, string $target): bool

Beginnt eine Verarbeitungsvorschrift.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

target

Ziel der Verarbeitungsvorschrift.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::endPi() - Beendet Verarbeitungsvorschrift
  • XMLWriter::writePi() - Komplette Verarbeitungsvorschrift-Tag schreiben

User Contributed Notes

There are no user contributed notes for this page.


Text schreiben

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Text schreiben

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Text schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::text(string $content): bool

Prozeduraler Stil

xmlwriter_text(XMLWriter $writer, string $content): bool

Schreibt einen Text.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

content

Textinhalt. Die Zeichen <, >, & und " werden als Entityreferenzen geschrieben (d.h. &lt;, &gt;, &amp; bzw. &quot;). Alle anderen Zeichen inklusive ' werden buchstäblich geschrieben. Um die speziellen XML Zeichen buchstäblich, oder um buchstäbliche Entityreferenzen zu schreiben, muss xmlwriter_write_raw() verwendet werden.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

User Contributed Notes

There are no user contributed notes for this page.


Komplettes Attribut schreiben

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Komplettes Attribut schreiben

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Komplettes Attribut schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeAttribute(string $name, string $value): bool

Prozeduraler Stil

xmlwriter_write_attribute(XMLWriter $writer, string $name, string $value): bool

Schreibt ein vollständiges Attribut.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name des Attributs.

value

Wert des Attributs.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Beispiele

Beispiel #1 Mischen von Kindelementen und Attributen

Werden Kindelemente und Attribute gemischt, wird jeder Versuch Attribute nach dem ersten Kindelement zu schreiben fehlschlagen, und false zurückgeben.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(false)
<element attr1="0"><subelem>0</subelem></element>

Siehe auch

  • XMLWriter::writeAttributeNs() - Komplettes Attribute mit Namensraum schreiben
  • XMLWriter::startAttribute() - Attribut beginnen
  • XMLWriter::startAttributeNs() - Namensraum-Attribut beginnen
  • XMLWriter::endAttribute() - Attribute beenden

User Contributed Notes

There are no user contributed notes for this page.


Komplettes Attribute mit Namensraum schreiben

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Komplettes Attribute mit Namensraum schreiben

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 — Komplettes Attribute mit Namensraum schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Prozeduraler Stil

xmlwriter_write_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Schreibt ein vollständiges Attribute mit Namensraum.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

prefix

Präfix des Namensraum. Ist prefix null, wird der Namesraum ausgelassen.

name

Name des Attributs.

namespace

URI des Namensraum. Ist namespace null, wird die Namensraumdeklaration ausgelassen.

value

Wert des Attributs.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::writeAttribute() - Komplettes Attribut schreiben
  • XMLWriter::startAttribute() - Attribut beginnen
  • XMLWriter::startAttributeNs() - Namensraum-Attribut beginnen
  • XMLWriter::endAttribute() - Attribute beenden

User Contributed Notes

There are no user contributed notes for this page.


Kompletten CDATA-Block schreiben

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Kompletten CDATA-Block schreiben

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Kompletten CDATA-Block schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeCdata(string $content): bool

Prozeduraler Stil

xmlwriter_write_cdata(XMLWriter $writer, string $content): bool

Schreibt einen vollständigen CDATA-Block.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

content

Inhalt des CDATA-Blocks.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Beispiele

Beispiel #1 Grundsätzliche xmlwriter_write_cdata() Verwendung

<?php
// Dokument einrichten
$xml = new XmlWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData schreiben
$xml->startElement('mycdataelement');
$xml->writeCData("Text zum Hinzufügen als CData");
$xml->endElement();

// Dokument beenden und ausgeben
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

<mydoc>
 <myele>
  <mycdataelement><![CDATA[Text zum Hinzufügen als CData]?]></mycdataelement>
 </myele>
</mydoc>

Siehe auch

  • XMLWriter::startCdata() - CDATA-Block beginnen
  • XMLWriter::endCdata() - Beendet CDATA-Block

User Contributed Notes

There are no user contributed notes for this page.


Kompletten Kommentar schreiben

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • Kompletten Kommentar schreiben

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Kompletten Kommentar schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeComment(string $content): bool

Prozeduraler Stil

xmlwriter_write_comment(XMLWriter $writer, string $content): bool

Schreibt einen vollständigen Kommentar.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

content

Inhalt des Kommentars.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startComment() - Kommentar beginnen
  • XMLWriter::endComment() - Beendet Kommentar

User Contributed Notes

There are no user contributed notes for this page.


Komplettes DTD-Tag schreiben

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Komplettes DTD-Tag schreiben

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Komplettes DTD-Tag schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Prozeduraler Stil

xmlwriter_write_dtd(
XMLWriter $writer,
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Schreibt einen vollständigen DTD-Tag.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

DTD-Name.

publicId

Public Identifier für PUBLIC.

systemId

Public Identifier für SYSTEM.

content

Inhalt des DTD-Tags.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtd() - DTD beginnen
  • XMLWriter::endDtd() - Beendet DTD

User Contributed Notes

There are no user contributed notes for this page.


Komplette DTD-Attributliste schreiben

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Komplette DTD-Attributliste schreiben

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 — Komplette DTD-Attributliste schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeDtdAttlist(string $name, string $content): bool

Prozeduraler Stil

xmlwriter_write_dtd_attlist(XMLWriter $writer, string $name, string $content): bool

Schreibt eine vollständige DTD-Attributliste.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name der DTD-Attributliste.

content

Inhalt der DTD-Attributliste.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtdAttlist() - DTD-Attributliste beginnen
  • XMLWriter::endDtdAttlist() - Beendet DTD-Attributliste

User Contributed Notes

There are no user contributed notes for this page.


Komplettes DTD-Element schreiben

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Komplettes DTD-Element schreiben

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 — Komplettes DTD-Element schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeDtdElement(string $name, string $content): bool

Prozeduraler Stil

xmlwriter_write_dtd_element(XMLWriter $writer, string $name, string $content): bool

Schreibt ein vollständiges DTD-Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name des DTD-Elements.

content

Inhalt des DTD-Elements.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startDtdElement() - DTD-Element beginnen
  • XMLWriter::endDtdElement() - Beendet DTD-Element

User Contributed Notes

There are no user contributed notes for this page.


Komplette DTD-Entität schreiben

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Komplette DTD-Entität schreiben

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 — Komplette DTD-Entität schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Prozeduraler Stil

xmlwriter_write_dtd_entity(
XMLWriter $writer,
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Schreibt eine vollständige DTD-Entität.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name der Entität.

content

Inhalt der Entität.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.
8.0.0 | publicId, systemId und notationData sind nun nullbar.

Siehe auch

  • XMLWriter::startDtdEntity() - DTD-Entität beginnen
  • XMLWriter::endDtdEntity() - Beendet DTD-Entität

User Contributed Notes

There are no user contributed notes for this page.


Komplettes Element schreiben

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Komplettes Element schreiben

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Komplettes Element schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeElement(string $name, ?string $content = null): bool

Prozeduraler Stil

xmlwriter_write_element(XMLWriter $writer, string $name, ?string $content = null): bool

Schreibt ein vollständiges Element.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

name

Name des Elements.

content

Inhalt des Elements.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startElement() - Element beginnen
  • XMLWriter::endElement() - Beendet Element
  • XMLWriter::writeElementNs() - Komplettes Element mit Namensraum schreiben

User Contributed Notes

There are no user contributed notes for this page.


Komplettes Element mit Namensraum schreiben

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Komplettes Element mit Namensraum schreiben

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 — Komplettes Element mit Namensraum schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Prozeduraler Stil

xmlwriter_write_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Schreibt ein vollständiges Element mit Namensraum.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

prefix

Präfix des Namensraum. Ist prefix null, wird der Namesraum ausgelassen.

name

Name des Elements.

namespace

URI des Namensraum. Ist namespace null, wird die Namensraumdeklaration ausgelassen.

content

Inhalt des Elements.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startElementNs() - Element mit Namensraum beginnen
  • XMLWriter::endElement() - Beendet Element
  • XMLWriter::writeElement() - Komplettes Element schreiben

User Contributed Notes

There are no user contributed notes for this page.


Komplette Verarbeitungsvorschrift-Tag schreiben

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Komplette Verarbeitungsvorschrift-Tag schreiben

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Komplette Verarbeitungsvorschrift-Tag schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writePi(string $target, string $content): bool

Prozeduraler Stil

xmlwriter_write_pi(XMLWriter $writer, string $target, string $content): bool

Schreibt einen vollständigen Verarbeitungsvorschrift-Tag.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

target

Ziel der Verarbeitungsvorschrift.

content

Inhalt der Verarbeitungsvorschrift.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::startPi() - Verarbeitungsvorschrift beginnen
  • XMLWriter::endPi() - Beendet Verarbeitungsvorschrift

User Contributed Notes

There are no user contributed notes for this page.


Reines XML schreiben

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Reines XML schreiben

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Reines XML schreiben

Beschreibung

Objektorientierter Stil

public XMLWriter::writeRaw(string $content): bool

Prozeduraler Stil

xmlwriter_write_raw(XMLWriter $writer, string $content): bool

Schreibt reinen XML Inhalt.

Parameter-Liste

writer

Nur für prozedurale Aufrufe. Die XMLWriter-Instanz, die bearbeitet werden soll. Dieses Objekt wird von Aufrufen von xmlwriter_open_uri() oder xmlwriter_open_memory() geliefert.

content

Zeichenkette, die geschrieben werden soll.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version | Beschreibung
8.0.0 | writer erwartet nun eine XMLWriter-Instanz; vorher wurde eine Ressource erwartet.

Siehe auch

  • XMLWriter::text() - Text schreiben

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
    • Laufzeit-Konfiguration
    • Ressource-Typen
  • Vordefinierte Konstanten
  • Beispiele
    • Die Beispieldateien collection.xml und collection.xsl
    • Fehlerbehandlung mit den Funktionen der libxml
  • XSLTProcessor — Die Klasse XSLTProcessor
    • XSLTProcessor::__construct — Erzeugt ein neues XSLTProcessor-Objekt
    • XSLTProcessor::getParameter — Liefert den Wert eines Parameters
    • XSLTProcessor::getSecurityPrefs — Liefert die Sicherheitseinstellungen
    • XSLTProcessor::hasExsltSupport — Prüft, ob die EXSLT-Unterstützung aktiviert ist
    • XSLTProcessor::importStylesheet — Importiert ein Stylesheet
    • XSLTProcessor::registerPHPFunctions — Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen
    • XSLTProcessor::removeParameter — Löscht einen Parameter
    • XSLTProcessor::setParameter — Setzt den Wert für einen Parameter
    • XSLTProcessor::setProfiling — Setzt den Dateinamen für die Ausgaben des Profilers
    • XSLTProcessor::setSecurityPrefs — Setzt die Sicherheitseinstellungen
    • XSLTProcessor::transformToDoc — Transformiert in ein Dokument
    • XSLTProcessor::transformToUri — Transformiert in einen URI
    • XSLTProcessor::transformToXml — Transformiert in einen XML-String

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


Einführung

Die XSL Erweiterung implementiert den XSL-Standard und erlaubt » XSLT Transformationen unter Verwendung der » libxslt-Bibliothek.

User Contributed Notes

There are no user contributed notes for this page.


Anforderungen

Diese Erweiterung erfordert die Erweiterung libxml. Das heißt, dass die Übergabe von --with-libxml, oder vor PHP 7.4.0 --enable-libxml, ebenfalls benötigt wird. Dies wird jedoch implizit erfüllt, da libxml standardmäßig aktiviert wird.

Um diese Erweiterung verwenden zu können, muß die Bibliothek libxslt in der Version 1.1.0 oder höher installiert sein. Sie steht unter » http://xmlsoft.org/XSLT/ zum Download bereit.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Die Erweiterung XSL ist in PHP enthalten und kann über die Option --with-xsl[=DIR] in Ihrer Build-Konfiguration aktiviert werden. Dabei steht DIR für das Installationsverzeichnis der libxslt-Bibliothek.

User Contributed Notes

There are no user contributed notes for this page.


Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verfügung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

XSL_CLONE_AUTO (int)
XSL_CLONE_NEVER (int)
XSL_CLONE_ALWAYS (int)
LIBXSLT_VERSION (int)
Version der libxslt als Zahl, beispielsweise 10117.
LIBXSLT_DOTTED_VERSION (string)
Version der libxslt als String, beispielsweise 1.1.17.
LIBEXSLT_VERSION (int)
Version der libexslt als Zahl, beispielsweise 813.
LIBEXSLT_DOTTED_VERSION (string)
Version der libexslt als String, beispielsweise 1.1.17.
XSL_SECPREF_NONE (int)
Schaltet sämtliche Sicherheitsrestriktionen aus
XSL_SECPREF_READ_FILE (int)
Verbietet den lesenden Zugriff auf Dateien
XSL_SECPREF_WRITE_FILE (int)
Verbietet den schreibenden Zugriff auf Dateien
XSL_SECPREF_CREATE_DIRECTORY (int)
Verbietet das Erzeugen von Verzeichnissen
XSL_SECPREF_READ_NETWORK (int)
Verbietet den lesenden Zugriff auf Dateien über das Netzwerk
XSL_SECPREF_WRITE_NETWORK (int)
Verbietet den schreibenden Zugriff auf Dateien über das Netzwerk
XSL_SECPREF_DEFAULT (int)
Verbietet sämtliche Schreibzugriffe; identisch mit der Bitmaske von XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.

User Contributed Notes

There are no user contributed notes for this page.


Beispiele

Inhaltsverzeichnis

  • Die Beispieldateien collection.xml und collection.xsl
  • Fehlerbehandlung mit den Funktionen der libxml

User Contributed Notes

There are no user contributed notes for this page.


Die Beispieldateien collection.xml und collection.xsl

Viele Beispiele in dieser Referenz erfordern sowohl eine XML- als auch XSL-Datei. Die Dateien collection.xml und collection.xsl bestehen jeweils aus folgendem Inhalt:

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

Beispiel #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.


Fehlerbehandlung mit den Funktionen der libxml

libxml bietet Funktionen zur Verarbeitung von Fehlern, die auch dafür verwendet werden können Fehler bei der Verarbeitung von XSLT abzufangen.

Beispiel #1 fruits.xml

Eine gültige XML-Datei.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Beispiel #2 fruits.xsl

Enthält einen ungültigen Ausdruck im select.

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

Beispiel #3 Sammel und ausgaben der Fehler

Das Beispiel unten sammelt die Fehlermeldungen die beim Aufruf des fehlerhaften Stylesheets mittels XSLTProcessor::importStyleSheet() durch libxml erzeugt werden und gibt sie kontrolliert aus.

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

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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.


Die Klasse XSLTProcessor

(PHP 5, PHP 7, PHP 8)

Einführung

Klassenbeschreibung

class XSLTProcessor {
/* Methoden */
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
}

Inhaltsverzeichnis

  • XSLTProcessor::__construct — Erzeugt ein neues XSLTProcessor-Objekt
  • XSLTProcessor::getParameter — Liefert den Wert eines Parameters
  • XSLTProcessor::getSecurityPrefs — Liefert die Sicherheitseinstellungen
  • XSLTProcessor::hasExsltSupport — Prüft, ob die EXSLT-Unterstützung aktiviert ist
  • XSLTProcessor::importStylesheet — Importiert ein Stylesheet
  • XSLTProcessor::registerPHPFunctions — Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen
  • XSLTProcessor::removeParameter — Löscht einen Parameter
  • XSLTProcessor::setParameter — Setzt den Wert für einen Parameter
  • XSLTProcessor::setProfiling — Setzt den Dateinamen für die Ausgaben des Profilers
  • XSLTProcessor::setSecurityPrefs — Setzt die Sicherheitseinstellungen
  • XSLTProcessor::transformToDoc — Transformiert in ein Dokument
  • XSLTProcessor::transformToUri — Transformiert in einen URI
  • XSLTProcessor::transformToXml — Transformiert in einen XML-String

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


Erzeugt ein neues XSLTProcessor-Objekt

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Erzeugt ein neues XSLTProcessor-Objekt

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Erzeugt ein neues XSLTProcessor-Objekt

Beschreibung

XSLTProcessor::__construct()

Erzeugt ein neues XSLTProcessor-Objekt.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Beispiele

Beispiel #1 Verwendung von 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.


Liefert den Wert eines Parameters

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Liefert den Wert eines Parameters

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Liefert den Wert eines Parameters

Beschreibung

public XSLTProcessor::getParameter(string $namespace, string $name): string|false

Liefert den Wert eines mittels XSLTProcessor::setParameter() gesetzten Parameters.

Parameter-Liste

namespace

Die Namespace-URI des XSLT-Parameters.

name

Der lokale Name des Parameters.

Rückgabewerte

Der Wert des Parameters (als String) oder false, falls kein Wert gesetzt ist.

Siehe auch

  • XSLTProcessor::setParameter() - Setzt den Wert für einen Parameter
  • XSLTProcessor::removeParameter() - Löscht einen Parameter

User Contributed Notes

There are no user contributed notes for this page.


Liefert die Sicherheitseinstellungen

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Liefert die Sicherheitseinstellungen

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Liefert die Sicherheitseinstellungen

Beschreibung

public XSLTProcessor::getSecurityPrefs(): int

Liefert die Sicherheitseinstellungen

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Eine Bitmaske bestehend aus XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.

User Contributed Notes

There are no user contributed notes for this page.


Prüft, ob die EXSLT-Unterstützung aktiviert ist

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Prüft, ob die EXSLT-Unterstützung aktiviert ist

XSLTProcessor::hasExsltSupport

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

XSLTProcessor::hasExsltSupport — Prüft, ob die EXSLT-Unterstützung aktiviert ist

Beschreibung

public XSLTProcessor::hasExsltSupport(): bool

Diese Methode ermittelt, ob PHP mit Unterstützung für die » EXSLT-Bibliothek kompiliert wurde.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

Beispiel #1 Prüfen auf EXSLT-Unterstützung

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
die('EXSLT nicht verfügbar');
}

// Weitere Verarbeitung ..

?>

User Contributed Notes

There are no user contributed notes for this page.


Importiert ein Stylesheet

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Importiert ein Stylesheet

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Importiert ein Stylesheet

Beschreibung

public XSLTProcessor::importStylesheet(object $stylesheet): bool

Diese Methode importiert ein Stylesheet in das XSLTProcessor-Objekt zur Transformierung.

Parameter-Liste

stylesheet

Das zu importierende Stylesheet in Form eines DOMDocument- oder SimpleXMLElement-Objekts.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

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!


Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen

XSLTProcessor::registerPHPFunctions

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

XSLTProcessor::registerPHPFunctions — Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen

Beschreibung

public XSLTProcessor::registerPHPFunctions(array|string|null $functions = null): void

Diese Methode aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen innerhalb eines XSL-Stylesheets.

Parameter-Liste

functions

Dieser Parameter ermöglicht es, die via XSL aufrufbaren Funktionen einzuschränken.

Der übergebene Wert kann entweder ein String (der Name einer Funktion) oder ein Array mit Funktionsnamen sein.

Rückgabewerte

Es wird kein Wert zurückgegeben.

Beispiele

Beispiel #1 Einfacher Aufruf einer PHP-Funktion durch ein Stylesheet

<?php
$xml = <<<EOB
<allusers>
<user>
<uid>bob</uid>
</user>
<user>
<uid>joe</uid>
</user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="allusers">
<html><body>
<h2>Benutzer</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


Löscht einen Parameter

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Löscht einen Parameter

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Löscht einen Parameter

Beschreibung

public XSLTProcessor::removeParameter(string $namespace, string $name): bool

Löscht, wenn gesetzt, den Wert eines Parameters. Sofern im Stylesheet mit Standardwert definiert, wird dieser vom Prozessor verwendet.

Parameter-Liste

namespace

Die Namespace-URI des XSLT-Parameters.

name

Der lokale Name des Parameters.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Siehe auch

  • XSLTProcessor::setParameter() - Setzt den Wert für einen Parameter
  • XSLTProcessor::getParameter() - Liefert den Wert eines Parameters

User Contributed Notes

There are no user contributed notes for this page.


Setzt den Wert für einen Parameter

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Setzt den Wert für einen Parameter

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Setzt den Wert für einen Parameter

Beschreibung

public XSLTProcessor::setParameter(string $namespace, string $name, string $value): bool
public XSLTProcessor::setParameter(string $namespace, array $options): bool

Setzt den Wert von einem oder mehreren Parametern zur Verwendung bei Transformationen mittels XSLTProcessor. Falls ein Parameter im Stylesheet nicht existiert wird der angegebene Wert ignoriert.

Parameter-Liste

namespace

Die Namespace-URI des XSLT-Parameters.

name

Der lokale Name des Parameters.

value

Der neue Wert für den XSLT-Parameter.

options

Ein assoziatives Array mit name => wert-Paaren.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Beispiele

Beispiel #1 Ändern des Parameters "owner" vor der Transformation

<?php

$collections = array(
'Marc Rutkowski' => 'marc',
'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Prozessor konfigurieren
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // Stylesheet anhängen

foreach ($collections as $name => $file) {
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection_' . $file . '.xml');

$proc->setParameter('', 'owner', $name);
$proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Siehe auch

  • XSLTProcessor::getParameter() - Liefert den Wert eines Parameters
  • XSLTProcessor::removeParameter() - Löscht einen Parameter

User Contributed Notes

richard at aggmedia dot net 04-Mar-2009 07:47
Note that there is no way to remove a parameter from an XSLTProcessor unless you know its name, and there is no way (that I can find) to get a list of the current parameters.

This means that you cannot reuse an XSLTProcessor with different parameters unless you call XSLTProcessor->removeParameter() on every parameter, and to do that you need to know the names of all the currently set parameters.

I bumped into this because we were caching XSLTProcessors for reuse, and they were spitting out content based on phantom parameters (they were still there from previous uses).
Lennaert van der Linden 13-Feb-2008 06:28
The parameter will not be set if the value contains both single and double quotes. Instead a warning will be shown when transforming the document:

PHP Warning:  XSLTProcessor::transformToXml(): Cannot create XPath expression (string contains both quote and double-quotes)
brettz9 08-May-2007 08:27
It seems heinemann's usage is not correct and does not achieve the intended result.

This method's purpose is to change a global <xsl:param> value in the XSL stylesheet--not to change an attribute of any other element.  <xsl:param> basically lets you set up a stylesheet which can be customized (as from PHP) externally (without needing to tamper with the original XSL file).

Here's an example of usage (that will work):

Stylesheet:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="print_something" select="defaultstring"/>
    <xsl:template match="/mydoc">
        <p style="color:red;">Printed parameter: <xsl:value-of select="$print_something"/></p>
    </xsl:template>
</xsl:stylesheet>

Script:

<?php
$dom = new DOMDocument();
$xsl = new XSLTProcessor;
$xsl->setParameter( '', 'print_something', "Now I've overridden the default!");
$style = realpath( "./my_stylesheet.xslt" );
$dom->load($style);
$xsl->importStyleSheet($dom);
$dom->loadXML('<mydoc></mydoc>');

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter('', 'print_something'),
'</pre>' );
?>

gives:

string(5) "

"
string(143) "<?xml version="1.0"?>
<p style="color:red;">Printed parameter: Now I've overridden the default!</p>
"
string(32) "Now I've overridden the default!"
string(6) "

"

Notice that at present adding a namespace will not work. The only option at present is to set the first parameter for namespace to an empty string (though you can add the prefix with colon to the second argument for name in order to set the parameter for a namespace-prefixed parameter name).

See http://bugs.php.net/bug.php?id=30622
OrionI 01-May-2007 07:19
After looking at this a little further (see http://bugs.php.net/bug.php?id=41248), it appears that it's a shortcoming of libxslt, not PHP, that prevents passing in DOMDocuments or DOMNodes as parameters.
Orion I 30-Apr-2007 08:46
I've been trying to pass in a DOMDocument object as a parameter so I can stuff a bunch of data into XML nodes, but it appears that this function is not capable of it. I was hoping to get it to work like it does in the .NET 2.0 framework. (See http://msdn2.microsoft.com/en-us/library/
system.xml.xsl.xsltargumentlist.addparam.aspx)
But after looking at the PHP 5.2.1 source code, /php-5.2.1/ext/xsl/xsltprocessor.c line 604-650, it appears that it's not possible to do so in PHP even though it appears that libxslt supports it (see http://xmlsoft.org/XSLT/html/libxslt-variables.html
#xsltParseGlobalParam)

In fact, if the parameters aren't exactly what's expected, you'll always get a warning like this:

Wrong parameter count for XSLTProcessor::setParameter()
heinemann dot juergen at hjcms dot de 07-Mar-2006 03:39
Example for how it works.

<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"
    indent="yes"
    encoding="ISO-8859-15"
    doctype-system = "-//W3C//DTD XHTML 1.0 Transitional//EN"
    doctype-public = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
/>
<xsl:template match="docs">
<html>
<head>
    <title>
        <xsl:text>Example</xsl:text>
    </title>
</head>
<body>
    <xsl:for-each select="block">
        <div>
            <xsl:value-of select="." />
        </div>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

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

<?php
$dom = new DomDocument( '1.0', 'utf-8' );
$xsl = new XSLTProcessor;
$xsl->setParameter( 'block', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$style = realpath( "./my_stylesheet.xslt" );
$dom->load( $style );
$xsl->importStyleSheet( $dom );

$dom->loadXML( '<docs>
    <block>Howto set xhtml Transitional Namespaces width php</block>
    <block>see http://www.php.net</block>
</docs>' );

$out = $xsl->transformToXML( $dom );

var_dump( '<pre>',
    htmlentities( $out, ENT_QUOTES, 'utf-8' ),
    $xsl->getParameter( 'block', 'xmlns' ),
    $xsl->getParameter( 'docs', 'xmlns' ),
'</pre>' );

?>
Stoke A 11-Aug-2005 03:40
XSLTProcessor::removeParameter() won't work on parameters set via XSLTProcessor::setParameter(string namespace, array options) in 5.1+ -- they need to be set and removed one by one.


Setzt den Dateinamen für die Ausgaben des Profilers

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Setzt den Dateinamen für die Ausgaben des Profilers

XSLTProcessor::setProfiling

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

XSLTProcessor::setProfiling — Setzt den Dateinamen für die Ausgaben des Profilers

Beschreibung

public XSLTProcessor::setProfiling(?string $filename): true

Setzt den Namen der Datei für die Ausgaben des Profilers während der Verarbeitung eines Stylesheets.

Parameter-Liste

filename

Pfad zur Datei, in die die Informationen geschrieben werden

Rückgabewerte

Gibt immer true zurück.

Beispiele

Beispiel #1 Ausgabe des Profilers

<?php
// Laden der XML/XSL-Quelldokomente
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Prozessor instantiieren und konfigurieren
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // Anhängen der xsl-Regeln

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

Der obige Quelltext erzeugt ungefähr die nachfolgende Ausgabe in der angegebenen Zieldatei:

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.


Setzt die Sicherheitseinstellungen

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Setzt die Sicherheitseinstellungen

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Setzt die Sicherheitseinstellungen

Beschreibung

public XSLTProcessor::setSecurityPrefs(int $preferences): int

Setzt die Sicherheitseinstellungen.

Parameter-Liste

preferences

Die neuen Sicherheitseinstellungen. Die folgenden Konstanten können per OR verbunden werden: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternativ kann auch, XSL_SECPREF_NONE oder XSL_SECPREF_DEFAULT übergeben werden.

Rückgabewerte

Liefert die vorherigen Sicherheitseinstellungen zurück.

User Contributed Notes

There are no user contributed notes for this page.


Transformiert in ein Dokument

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri »
  • PHP Manual
  • XSLTProcessor
  • Transformiert in ein Dokument

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transformiert in ein Dokument

Beschreibung

public XSLTProcessor::transformToDoc(object $document, ?string $returnClass = null): object|false

Transformiert den Quellknoten in ein Dokument (z. B. DOMDocument, indem das mittels der Methode XSLTProcessor::importStylesheet() übergebene Stylesheet angewendet wird.

Parameter-Liste

document

Das zu verarbeitende DOMDocument-, SimpleXMLElement- oder libxml-kompatible Objekt

returnClass

Dieser optionale Parameter kann verwendet werden, damit XSLTProcessor::transformToDoc() ein Objekt der angegebenen Klasse zurückgibt. Diese Klasse sollte entweder die gleiche Klasse sein wie die von document oder diese erweitern.

Rückgabewerte

Das erzeugte Dokument oder false, falls ein Fehler aufgetreten ist.

Beispiele

Beispiel #1 Transformation in ein DOMDocument

<?php

// XML-Quelle laden
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Prozessor instanziieren und konfigurieren
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // die XSL-Regeln anhängen

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Siehe auch

  • XSLTProcessor::transformToUri() - Transformiert in einen URI
  • XSLTProcessor::transformToXml() - Transformiert in einen XML-String

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.


Transformiert in einen URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transformiert in einen URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToUri — Transformiert in einen URI

Beschreibung

public XSLTProcessor::transformToUri(object $document, string $uri): int

Transformiert den Quellknoten in einen URI, indem das mittels der Methode XSLTProcessor::importStylesheet() übergebene Stylesheet angewendet wird.

Parameter-Liste

document

Das zu verarbeitende DOMDocument- oder SimpleXMLElement-Objekt

uri

Der URI für das Ziel der Transformation.

Rückgabewerte

Gibt die Anzahl geschriebener Bytes zurück oder false, falls ein Fehler aufgetreten ist.

Beispiele

Beispiel #1 Transformation in eine HTML-Datei

<?php

// XML-Quelle laden
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Prozessor instanziieren und konfigurieren
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // die XSL-Regeln anhängen

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Siehe auch

  • XSLTProcessor::transformToDoc() - Transformiert in ein Dokument
  • XSLTProcessor::transformToXml() - Transformiert in einen XML-String

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


Transformiert in einen XML-String

  • « XSLTProcessor::transformToUri
  • GUI Erweiterungen »
  • PHP Manual
  • XSLTProcessor
  • Transformiert in einen XML-String

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transformiert in einen XML-String

Beschreibung

public XSLTProcessor::transformToXml(object $document): string|null|false

Transformiert den Quellknoten in einen String, indem das mittels der Methode XSLTProcessor::importStylesheet() übergebene Stylesheet angewendet wird.

Parameter-Liste

document

Das zu transformierende DOMDocument- oder SimpleXMLElement-Objekt.

Rückgabewerte

Das Ergebnis der Transformation als String oder false, falls ein Fehler aufgetreten ist.

Beispiele

Beispiel #1 Transformation in einen String

<?php

// XML-Quelle laden
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Prozessor instanziieren und konfigurieren
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // die XSL-Regeln anhängen

echo $proc->transformToXML($xml);

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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>

Siehe auch

  • XSLTProcessor::transformToDoc() - Transformiert in ein Dokument
  • XSLTProcessor::transformToUri() - Transformiert in einen 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.


GUI Erweiterungen

  • UI
    • Einführung
    • Installation/Konfiguration
    • 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 Funktionen
    • 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

  • Einführung
  • Installation/Konfiguration
    • Anforderungen
    • Installation
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Size Coercion
    • UI\Point::__construct — Construct a new Point
    • UI\Point::getX — Retrieves X
    • UI\Point::getY — Retrieves Y
    • UI\Point::setX — Set X
    • UI\Point::setY — Set Y
  • UI\Size — Represents dimensions (width, height)
    • UI\Size::__construct — Construct a new Size
    • UI\Size::getHeight — Retrieves Height
    • UI\Size::getWidth — Retrives Width
    • UI\Size::of — Point Coercion
    • UI\Size::setHeight — Set Height
    • UI\Size::setWidth — Set Width
  • UI\Window — Window
    • UI\Window::add — Add a Control
    • UI\Window::__construct — Construct a new Window
    • UI\Window::error — 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 Funktionen
    • 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.


Einführung

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.


Installation/Konfiguration

Inhaltsverzeichnis

  • Anforderungen
  • Installation

User Contributed Notes

shevegen at gmail dot com 14-Feb-2021 09:01
I believe this example is not correct; for example it shows "cmake" in
use but after you git clone the above URL, there are no cmake files.

So this can not possibly have worked; and I actually don't think there
ever was cmake used in the above repository, which makes you wonder
why the above code used cmake to begin with. Did it ever work? I am not sure;
I tend to assume it did not work.
whirlwind110 at 163 dot com 18-Apr-2017 04:04
Requirements:
    PHP 7
    libui (use current master)
    Windows/MacOSX/Linux (GTK-3)

Install re2c:
    sudo apt install re2c

Install libui:

    git clone https://github.com/andlabs/libui.git
    cd libui
    sudo cp *.h /usr/local/include/
    cmake .
    cd out
    sudo cp * /usr/lib/

Install ui:

    Method one: use pecl:
        sudo pecl install channel://pecl.php.net/ui-2.0.0

    Method two:build source code:
        git clone https://github.com/krakjoe/ui.git
        cd ui
        phpize
        make
        sudo make install

Enable ui.so:
    sudo echo 'extension=ui.so' > /etc/php/7.0/mods-available/ui.ini
    sudo ln -s /etc/php/7.0/mods-available/ui.ini 20-ui.ini

Test:
    php -m
    git clone https://github.com/krakjoe/ui.git
    cd ui/examples/
    php snake.php


Anforderungen

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.


Installation

Diese » PECL-Erweiterung ist nicht Teil von PHP.

Information zur Installation dieser PECL-Erweiterung finden sie im Kapitel Installation von PECL-Erweiterungen. Zusätzliche Informationen wie neue Releases, Downloads, Quelldateien, Maintainerinformation und ein CHANGELOG finden Sie hier: » https://pecl.php.net/package/ui.

Windows-Binaries (DLL-Dateien) für diese PECL-Erweiterung sind auf der PECL-Website erhältlich.

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

Einführung

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Klassenbeschreibung

final class UI\Point {
/* Eigenschaften */
public $x;
public $y;
/* Constructor */
public __construct(float $x, float $y)
/* Methoden */
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)
}

Eigenschaften

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

point

The value for x and y

size

The Size to convert

Rückgabewerte

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

Beschreibung

public UI\Point::__construct(float $x, float $y)

Construct a new Point using new co-ordinates

Parameter-Liste

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

Beschreibung

public UI\Point::getX(): float

Retrieves the X co-ordinate

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Point::getY(): float

Retrieves the Y co-ordinate

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Point::setX(float $point)

Set the X co-ordinate

Parameter-Liste

point

The new X co-ordinate

Rückgabewerte

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

Beschreibung

public UI\Point::setY(float $point)

Set the Y co-ordinate

Parameter-Liste

point

The new Y co-ordinate

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Represents dimensions (width, height)

(UI 0.9.9)

Einführung

Sizes are used throughout UI to represent the size of a screen, control, or area.

Klassenbeschreibung

final class UI\Size {
/* Eigenschaften */
public $width;
public $height;
/* Constructor */
public __construct(float $width, float $height)
/* Methoden */
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)
}

Eigenschaften

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Size::__construct(float $width, float $height)

Construct a new Size using new width and height

Parameter-Liste

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

Beschreibung

public UI\Size::getHeight(): float

Retrieves the Height

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Size::getWidth(): float

Retrieves the Width

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

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

Parameter-Liste

size

The value for width and height

point

The Point to convert

Rückgabewerte

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

Beschreibung

public UI\Size::setHeight(float $size)

Set new Height

Parameter-Liste

size

The new Height

Rückgabewerte

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

Beschreibung

public UI\Size::setWidth(float $size)

Set new Width

Parameter-Liste

size

The new Width

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

Einführung

Represents a UI Window

Klassenbeschreibung

class UI\Window extends UI\Control {
/* Eigenschaften */
protected $controls;
/* Constructor */
public __construct(string $title, Size $size, bool $menu = false)
/* Methoden */
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)
/* Geerbte Methoden */
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()
}

Eigenschaften

controls

Contains controls, should not be manipulated directly

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Window::add(UI\Control $control)

Shall add a Control to this Window

Parameter-Liste

control

The Control to add

Rückgabewerte

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

Beschreibung

public UI\Window::__construct(string $title, Size $size, bool $menu = false)

Shall construct a new Window

Parameter-Liste

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

Beschreibung

public UI\Window::error(string $title, string $msg)

Shall show an error box

Parameter-Liste

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

Beschreibung

public UI\Window::getSize(): UI\Size

Shall return the size of this Window

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::getTitle(): string

Shall retrieve the title of this Window

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::hasBorders(): bool

Shall detect if borders are used on this Window

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::hasMargin(): bool

Shall detect if margins are used on this Window

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::isFullScreen(): bool

Shall detect if this Window us using the whole screen

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::msg(string $title, string $msg)

Shall show a message box

Parameter-Liste

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

Beschreibung

protected UI\Window::onClosing(): int

Should gracefully destroy this Window

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::open(): string

Shall show an open file dialog

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::save(): string

Shall show a save dialog

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Window::setBorders(bool $borders)

Shall enable or disable the use of borders on this Window

Parameter-Liste

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

Beschreibung

public UI\Window::setFullScreen(bool $full)

Shall enable or disable the use of the full screen for this Window

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Parameter zur Verfügung.

Parameter-Liste

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

Beschreibung

public UI\Window::setMargin(bool $margin)

Shall enable or disable the use of margins for this Window

Parameter-Liste

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

Beschreibung

public UI\Window::setSize(UI\Size $size)

Shall set the size of this Window

Parameter-Liste

size

Rückgabewerte

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

Beschreibung

public UI\Window::setTitle(string $title)

Shall set the title for this Window

Parameter-Liste

title

The new title

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

Einführung

This is the closed base class for all UI Controls.

Klassenbeschreibung

final class UI\Control {
/* Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Control::destroy()

Shall destroy this Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::disable()

Shall disable this Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::enable()

Shall enable this Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::getParent(): UI\Control

Shall return the parent Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::getTopLevel(): int

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Parameter zur Verfügung.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::hide()

Shall hide this Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::isEnabled(): bool

Shall detect if this Control is enabled

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::isVisible(): bool

Shall detect if this Control is visible

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Control::setParent(UI\Control $parent)

Shall set the parent Control of this Control

Parameter-Liste

parent

The parent Control

Rückgabewerte

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

Beschreibung

public UI\Control::show()

Shall show this Control

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

Einführung

Menus must be constructed before the first Window, and can be shown on any Window

Klassenbeschreibung

class UI\Menu {
/* Constructor */
public __construct(string $name)
/* Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Menu::append(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a new Menu Item

Parameter-Liste

name

The name (text) for the new item

type

The type for the new item

Rückgabewerte

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

Beschreibung

public UI\Menu::appendAbout(string $type = UI\MenuItem::class): UI\MenuItem

Shall append an About menu item

Parameter-Liste

type

The type for the new item

Rückgabewerte

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

Beschreibung

public UI\Menu::appendCheck(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a checkable menu item

Parameter-Liste

name

The name (text) for the new item

type

The type for the new item

Rückgabewerte

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

Beschreibung

public UI\Menu::appendPreferences(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Preferences menu item

Parameter-Liste

type

The type for the new item

Rückgabewerte

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

Beschreibung

public UI\Menu::appendQuit(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Quit menu item

Parameter-Liste

type

The type for the new item

Rückgabewerte

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

Beschreibung

public UI\Menu::appendSeparator()

Shall append a separator

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Menu::__construct(string $name)

Shall construct a new Menu

Parameter-Liste

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)

Einführung

Menu Items should only be created by the Menu

Klassenbeschreibung

class UI\MenuItem {
/* Methoden */
public disable()
public enable()
public isChecked(): bool
protected onClick()
public setChecked(bool $checked)
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\MenuItem::disable()

Shall disable this Menu Item

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\MenuItem::enable()

Shall enable this Menu Item

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\MenuItem::isChecked(): bool

Shall detect if this Menu Item is checked

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\MenuItem::onClick()

Shall be executed when this Menu Item is clicked

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\MenuItem::setChecked(bool $checked)

Shall set the checked status of this Menu Item

Parameter-Liste

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

Einführung

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Klassenbeschreibung

class UI\Area extends UI\Control {
/* Konstanten */
const int Ctrl;
const int Alt;
const int Shift;
const int Super;
const int Down;
const int Up;
/* Methoden */
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)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

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

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

protected UI\Area::onKey(string $key, int $ext, int $flags)

Shall be executed on key events

Parameter-Liste

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Rückgabewerte

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

Beschreibung

protected UI\Area::onMouse(UI\Point $areaPoint, UI\Size $areaSize, int $flags)

Shall be executed on mouse events

Parameter-Liste

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

Beschreibung

public UI\Area::redraw()

Requests that this Area is redrawn

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Area::scrollTo(UI\Point $point, UI\Size $size)

Scroll this Area

Parameter-Liste

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

Beschreibung

public UI\Area::setSize(UI\Size $size)

Sets the size of this Area

Parameter-Liste

size

The new size

User Contributed Notes

There are no user contributed notes for this page.


Execution Scheduler

(UI 2.0.0)

Einführung

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Klassenbeschreibung

abstract class UI\Executor {
/* Constructor */
public __construct()
public __construct(int $microseconds)
public __construct(int $seconds, int $microseconds)
/* Methoden */
public kill(): void
abstract protected onExecute(): void
public setInterval(int $microseconds): bool
public setInterval(int $seconds, int $microseconds): bool
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Executor::kill(): void

Shall stop an executor, the executor cannot be restarted

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

abstract protected UI\Executor::onExecute(): void

Shall be repetitively queued for execution in the main thread

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

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

Parameter-Liste

seconds

microseconds

Rückgabewerte

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

Einführung

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Klassenbeschreibung

class UI\Controls\Tab extends UI\Control {
/* Eigenschaften */
protected $controls;
/* Methoden */
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)
/* Geerbte Methoden */
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()
}

Eigenschaften

controls

Contains controls, should not be manipulated directly

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Tab::append(string $name, UI\Control $control): int

Append a new page to this Tab

Parameter-Liste

name

The name for the new page

control

The control for the new page

Rückgabewerte

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

Beschreibung

public UI\Controls\Tab::delete(int $index): bool

Shall remove the selected page from this Tab

Parameter-Liste

index

The index of the page to remove

Rückgabewerte

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

Beschreibung

public UI\Controls\Tab::hasMargin(int $page): bool

Shall detect if the given page has a margin.

Parameter-Liste

page

The index of the page

Rückgabewerte

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

Beschreibung

public UI\Controls\Tab::insertAt(string $name, int $page, UI\Control $control)

Shall insert a new page into this Tab

Parameter-Liste

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

Beschreibung

public UI\Controls\Tab::pages(): int

Shall return the number of pages in this Tab

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Controls\Tab::setMargin(int $page, bool $margin)

Shall enable or disable margins on the selected page

Parameter-Liste

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)

Einführung

A Check is a labelled checkable box

Klassenbeschreibung

class UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methoden */
public getText(): string
public isChecked(): bool
protected onToggle()
public setChecked(bool $checked)
public setText(string $text)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Check::__construct(string $text)

Shall construct a new Check

Parameter-Liste

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

Beschreibung

public UI\Controls\Check::getText(): string

Shall return the text (label) for this Check

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Controls\Check::isChecked(): bool

Shall detect the status of this Check

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\Check::onToggle()

Shall be executed when the status of this Check is changed

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Check::setChecked(bool $checked)

Shall change the status of this Check

Parameter-Liste

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

Beschreibung

public UI\Controls\Check::setText(string $text)

Shall set the text (label) for this Check

Parameter-Liste

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


Button Control

(UI 0.9.9)

Einführung

Represents a labelled clickable button

Klassenbeschreibung

class UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methoden */
public getText(): string
protected onClick()
public setText(string $text)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Button::__construct(string $text)

Shall construct a new Button

Parameter-Liste

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

Beschreibung

public UI\Controls\Button::getText(): string

Shall retrieve the text (label) for this Button

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

protected UI\Controls\Button::onClick()

Shall be executed when this Button is clicked

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Button::setText(string $text)

Shall set the text (label) for this Button

Parameter-Liste

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


ColorButton Control

(UI 0.9.9)

Einführung

A Color Button is a button which displays a color picker when clicked

Klassenbeschreibung

class UI\Controls\ColorButton extends UI\Control {
/* Methoden */
public getColor(): UI\Color
protected onChange()
public setColor(UI\Draw\Color $color)
public setColor(int $color)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\ColorButton::getColor(): UI\Color

Shall retrieve the currently selected Color

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

protected UI\Controls\ColorButton::onChange()

Shall be executed when the selected Color is changed

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\ColorButton::setColor(UI\Draw\Color $color)
public UI\Controls\ColorButton::setColor(int $color)

Shall set the currently selected Color

Parameter-Liste

color

The new color

User Contributed Notes

There are no user contributed notes for this page.


Label Control

(UI 0.9.9)

Einführung

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Klassenbeschreibung

class UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methoden */
public getText(): string
public setText(string $text)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Label::__construct(string $text)

Shall construct a new Label

Parameter-Liste

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

Beschreibung

public UI\Controls\Label::getText(): string

Shall return the current text for this Label

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Parameter zur Verfügung.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Controls\Label::setText(string $text)

Shall set the text for this Label

Parameter-Liste

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Entry Control

(UI 0.9.9)

Einführung

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Klassenbeschreibung

class UI\Controls\Entry extends UI\Control {
/* Konstanten */
const int Normal;
const int Password;
const int Search;
/* Constructor */
public __construct(int $type = UI\Controls\Entry::Normal)
/* Methoden */
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Entry::__construct(int $type = UI\Controls\Entry::Normal)

Construct a new entry of the given type

Parameter-Liste

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

Beschreibung

public UI\Controls\Entry::getText(): string

Shall return the current text from this Entry

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Controls\Entry::isReadOnly(): bool

Shall detect if this Entry is read only

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

protected UI\Controls\Entry::onChange()

Shall be executed when the text in this Entry changes

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Entry::setReadOnly(bool $readOnly)

Shall enable or disable read only for this Entry

Parameter-Liste

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

Beschreibung

public UI\Controls\Entry::setText(string $text)

Shall set the text for this Entry

Parameter-Liste

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


MultilineEntry Control

(UI 0.9.9)

Einführung

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Klassenbeschreibung

class UI\Controls\MultilineEntry extends UI\Control {
/* Konstanten */
const int Wrap;
const int NoWrap;
/* Constructor */
public __construct(int $type = ?)
/* Methoden */
public append(string $text)
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\MultilineEntry::append(string $text)

Shall append the given text to the text in this Multiline Entry

Parameter-Liste

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

Beschreibung

public UI\Controls\MultilineEntry::__construct(int $type = ?)

Shall construct a new Multiline Entry of the given type

Parameter-Liste

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

Beschreibung

public UI\Controls\MultilineEntry::getText(): string

Shall return the text in this Multiline Entry

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\MultilineEntry::isReadOnly(): bool

Shall detect if this Multiline Entry is read only

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\MultilineEntry::onChange()

Shall be executed when the text in this Multiline Entry is changed

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\MultilineEntry::setReadOnly(bool $readOnly)

Shall enable or disable read only on this Multiline Entry

Parameter-Liste

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

Beschreibung

public UI\Controls\MultilineEntry::setText(string $text)

Shall set the text in this Multiline Entry

Parameter-Liste

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Spin Control

(UI 0.9.9)

Einführung

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Klassenbeschreibung

class UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Methoden */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Spin::__construct(int $min, int $max)

Constructs a new Spin with the given range

Parameter-Liste

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

Beschreibung

public UI\Controls\Spin::getValue(): int

Get the value in this Spin

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\Spin::onChange()

Shall be executed when the value in this Spin changes

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Spin::setValue(int $value)

Set the value in this Spin

Parameter-Liste

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Slider Control

(UI 0.9.9)

Einführung

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.

Klassenbeschreibung

class UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Methoden */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Slider::__construct(int $min, int $max)

Construct a new Slider with the given range

Parameter-Liste

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

Beschreibung

public UI\Controls\Slider::getValue(): int

Get the value from this Slider

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\Slider::onChange()

Shall be executed when the value of this Slider changes

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Slider::setValue(int $value)

Shall set the value for this Slider

Parameter-Liste

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Progress Control

(UI 0.9.9)

Einführung

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Klassenbeschreibung

class UI\Controls\Progress extends UI\Control {
/* Methoden */
public getValue(): int
public setValue(int $value)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Progress::getValue(): int

Shall retrieve the current value of this Progress bar

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Progress::setValue(int $value)

Shall set the value for this Progress bar

Parameter-Liste

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)

Einführung

A Separator represents a control separator, it has no other function.

Klassenbeschreibung

class UI\Controls\Separator extends UI\Control {
/* Konstanten */
const int Horizontal;
const int Vertical;
/* Constructor */
public __construct(int $type = UI\Controls\Separator::Horizontal)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Separator::__construct(int $type = UI\Controls\Separator::Horizontal)

Shall construct a new Separator of the given type

Parameter-Liste

type

Separator::Horizonal or Separator::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Combo Control

(UI 0.9.9)

Einführung

A Combo control represents a list of options, like the familiar select HTML element.

Klassenbeschreibung

class UI\Controls\Combo extends UI\Control {
/* Methoden */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Combo::append(string $text)

Append an option to this Combo

Parameter-Liste

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

Beschreibung

public UI\Controls\Combo::getSelected(): int

Shall retrieve the index of the option selected in this Combo

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\Combo::onSelected()

Shall be executed when an option is selected in this Combo

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Combo::setSelected(int $index)

Shall set the currently selected option in this Combo

Parameter-Liste

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)

Einführung

An Editable Combo is a Combo which allows the user to enter custom options

Klassenbeschreibung

class UI\Controls\EditableCombo extends UI\Control {
/* Methoden */
public append(string $text)
public getText(): string
protected onChange()
public setText(string $text)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\EditableCombo::append(string $text)

Shall append a new option to this Editable Combo

Parameter-Liste

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

Beschreibung

public UI\Controls\EditableCombo::getText(): string

Get the value of the currently selected option in this Editable Combo

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\EditableCombo::onChange()

Shall be executed when the value of this Editable Combobox changes

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\EditableCombo::setText(string $text)

Shall set the text of the currently selected option in this Editable Combo

Parameter-Liste

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Radio Control

(UI 0.9.9)

Einführung

A Radio is similar to the radio input type familiar from HTML

Klassenbeschreibung

class UI\Controls\Radio extends UI\Control {
/* Methoden */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Geerbte Methoden */
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()
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Radio::append(string $text)

Shall append a new option to this Radio

Parameter-Liste

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

Beschreibung

public UI\Controls\Radio::getSelected(): int

Shall retrieve the index of the currently selected option in this Radio

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

protected UI\Controls\Radio::onSelected()

Shall be executed when the option selected in this Radio changes

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Radio::setSelected(int $index)

Shall set the currently selected option in this Radio

Parameter-Liste

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)

Einführung

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Klassenbeschreibung

class UI\Controls\Picker extends UI\Control {
/* Konstanten */
const int Date;
const int Time;
const int DateTime;
/* Constructor */
public __construct(int $type = UI\Controls\Picker::Date)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Picker::__construct(int $type = UI\Controls\Picker::Date)

Construct a new Picker of the given type

Parameter-Liste

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)

Einführung

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Klassenbeschreibung

class UI\Controls\Form extends UI\Control {
/* Eigenschaften */
protected $controls;
/* Methoden */
public append(string $label, UI\Control $control, bool $stretchy = false): int
public delete(int $index): bool
public isPadded(): bool
public setPadded(bool $padded)
/* Geerbte Methoden */
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()
}

Eigenschaften

controls

Contains controls, should not be manipulated directly

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Rückgabewerte

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

Beschreibung

public UI\Controls\Form::delete(int $index): bool

Shall delete the control at the given index in this Form

Parameter-Liste

index

The index of the control to remove

Rückgabewerte

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

Beschreibung

public UI\Controls\Form::isPadded(): bool

Shall detect if padding is enabled on this Form

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Form::setPadded(bool $padded)

Shall enable or disable padding on this Form

Parameter-Liste

padded

User Contributed Notes

There are no user contributed notes for this page.


Control Grid (Arrangement)

(UI 0.9.9)

Einführung

A Grid is a control which is allows the arrangement of children into a grid

Klassenbeschreibung

class UI\Controls\Grid extends UI\Control {
/* Konstanten */
const int Fill;
const int Start;
const int Center;
const int End;
const int Leading;
const int Top;
const int Trailing;
const int Bottom;
/* Eigenschaften */
protected $controls;
/* Methoden */
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)
/* Geerbte Methoden */
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()
}

Vordefinierte Konstanten

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

Eigenschaften

controls

Contains controls, should not be manipulated directly

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Grid::append(
UI\Control $control,
int $left,
int $top,
int $xspan,
int $yspan,
bool $hexpand,
int $halign,
bool $vexpand,
int $valign
)

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Parameter zur Verfügung.

Parameter-Liste

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Rückgabewerte

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

Beschreibung

public UI\Controls\Grid::isPadded(): bool

Shall detect if padding is enabled on this Grid

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Grid::setPadded(bool $padding)

Shall enable or disable padding for this Grid

Parameter-Liste

padding

User Contributed Notes

There are no user contributed notes for this page.


Control Group (Arrangement)

(UI 0.9.9)

Einführung

A Group is a titled container for child controls

Klassenbeschreibung

class UI\Controls\Group extends UI\Control {
/* Eigenschaften */
protected $controls;
/* Constructor */
public __construct(string $title)
/* Methoden */
public append(UI\Control $control)
public getTitle(): string
public hasMargin(): bool
public setMargin(bool $margin)
public setTitle(string $title)
/* Geerbte Methoden */
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()
}

Eigenschaften

controls

Contains controls, should not be manipulated directly

Inhaltsverzeichnis

  • UI\Controls\Group::append — Append Control
  • UI\Controls\Group::__construct — Construct a new Group
  • UI\Controls\Group::getTitle — Get Title
  • UI\Controls\Group::hasMargin — Margin Detection
  • UI\Controls\Group::setMargin — Set Margin
  • UI\Controls\Group::setTitle — Set Title

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • « UI\Controls\Group
  • UI\Controls\Group::__construct »
  • PHP Manual
  • UI\Controls\Group
  • Append Control

UI\Controls\Group::append

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

UI\Controls\Group::append — Append Control

Beschreibung

public UI\Controls\Group::append(UI\Control $control)

Shall append a control to this Group

Parameter-Liste

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

Beschreibung

public UI\Controls\Group::__construct(string $title)

Shall construct a new Group with the given title

Parameter-Liste

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

Beschreibung

public UI\Controls\Group::getTitle(): string

Shall return the current title for this Group

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Controls\Group::hasMargin(): bool

Shall detect if this Group has a margin

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Group::setMargin(bool $margin)

Shall enable or disable margins for this Group

Parameter-Liste

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

Beschreibung

public UI\Controls\Group::setTitle(string $title)

Shall set the title for this Group

Parameter-Liste

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)

Einführung

A Box allows the arrangement of other controls

Klassenbeschreibung

class UI\Controls\Box extends UI\Control {
/* Konstanten */
const int Vertical;
const int Horizontal;
/* Eigenschaften */
protected $controls;
/* Constructor */
public __construct(int $orientation = UI\Controls\Box::Horizontal)
/* Methoden */
public append(Control $control, bool $stretchy = false): int
public delete(int $index): bool
public getOrientation(): int
public isPadded(): bool
public setPadded(bool $padded)
/* Geerbte Methoden */
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()
}

Eigenschaften

controls

Contains controls, should not be manipulated directly

Vordefinierte Konstanten

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Controls\Box::append(Control $control, bool $stretchy = false): int

Shall append the given control to this Box

Parameter-Liste

control

The control to append

stretchy

Set true to stretch the control

Rückgabewerte

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

Beschreibung

public UI\Controls\Box::__construct(int $orientation = UI\Controls\Box::Horizontal)

Shall construct a new box

Parameter-Liste

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

Beschreibung

public UI\Controls\Box::delete(int $index): bool

Shall delete the control at the given index from this Box

Parameter-Liste

index

The index of the control to delete

Rückgabewerte

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

Beschreibung

public UI\Controls\Box::getOrientation(): int

Shall retrieve the orientation of this Box

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Box::isPadded(): bool

Shall detect if padding is enabled on this Box

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Controls\Box::setPadded(bool $padded)

Shall enable or disable padding on this Box

Parameter-Liste

padded

User Contributed Notes

There are no user contributed notes for this page.


Draw Pen

(UI 0.9.9)

Einführung

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Klassenbeschreibung

final class UI\Draw\Pen {
/* Methoden */
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)
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Pen::clip(UI\Draw\Path $path)

Shall clip the given Path

Parameter-Liste

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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Pen::restore()

Shall restore a previously saved Pen

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Draw\Pen::save()

Shall save the Pen

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Pen::transform(UI\Draw\Matrix $matrix)

Shall perform matrix transformation

Parameter-Liste

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

Beschreibung

public UI\Draw\Pen::write(UI\Point $point, UI\Draw\Text\Layout $layout)

Shall draw the given text layout at the given point

Parameter-Liste

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)

Einführung

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Klassenbeschreibung

class UI\Draw\Path {
/* Konstanten */
const int Winding;
const int Alternate;
/* Constructor */
public __construct(int $mode = UI\Draw\Path::Winding)
/* Methoden */
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
)
}

Vordefinierte Konstanten

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Path::arcTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for an arc

Parameter-Liste

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

Rückgabewerte

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

Beschreibung

public UI\Draw\Path::bezierTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall draw a bezier curve

Parameter-Liste

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

Beschreibung

public UI\Draw\Path::closeFigure()

Shall close the current figure

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Draw\Path::__construct(int $mode = UI\Draw\Path::Winding)

Shall construct a new path in the given mode

Parameter-Liste

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

Beschreibung

public UI\Draw\Path::end()

Shall finalize this Path

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Draw\Path::lineTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for a line

Parameter-Liste

point

The point to begin mapping

radius

angle

sweep

negative

Rückgabewerte

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

Beschreibung

public UI\Draw\Path::newFigure(UI\Point $point)

Shall map a new figure at the given point

Parameter-Liste

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

Beschreibung

public UI\Draw\Path::newFigureWithArc(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Parameter-Liste

point

radius

angle

sweep

negative

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

Einführung

Klassenbeschreibung

class UI\Draw\Matrix {
/* Methoden */
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)
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Matrix::invert()

Shall invert this matrix

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Draw\Matrix::isInvertible(): bool

Shall detect if this Matrix may be inverted

Parameter-Liste

Diese Funktion besitzt keine Parameter.

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

Beschreibung

public UI\Draw\Matrix::multiply(UI\Draw\Matrix $matrix): UI\Draw\Matrix

Shall multiply this matrix with the given matrix

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Matrix::rotate(UI\Point $point, float $amount)

Shall rotate this Matrix

Parameter-Liste

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

Beschreibung

public UI\Draw\Matrix::scale(UI\Point $center, UI\Point $point)

Shall scale this Matrix

Parameter-Liste

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

Beschreibung

public UI\Draw\Matrix::skew(UI\Point $point, UI\Point $amount)

Shall skew this Matrix

Parameter-Liste

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

Beschreibung

public UI\Draw\Matrix::translate(UI\Point $point)

Shall translate this Matrix

Parameter-Liste

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

Einführung

Represents RGBA colours, individual channels are accessible via public properties.

Klassenbeschreibung

class UI\Draw\Color {
/* Konstanten */
const int Red;
const int Green;
const int Blue;
const int Alpha;
/* Eigenschaften */
public $r;
public $g;
public $b;
public $a;
/* Constructor */
public __construct(UI\Draw\Color $color = ?)
public __construct(int $color = ?)
/* Methoden */
public getChannel(int $channel): float
public setChannel(int $channel, float $value): void
}

Eigenschaften

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

Vordefinierte Konstanten

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

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Color::__construct(UI\Draw\Color $color = ?)
public UI\Draw\Color::__construct(int $color = ?)

Shall construct a new color

Parameter-Liste

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

Beschreibung

public UI\Draw\Color::getChannel(int $channel): float

Shall retrieve the value for a channel

Parameter-Liste

channel

Constant channel identity

Rückgabewerte

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

Beschreibung

public UI\Draw\Color::setChannel(int $channel, float $value): void

Shall set the selected channel to the given value

Parameter-Liste

channel

Constant channel identity

value

The new value for the selected channel

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

Einführung

Holds the configuration for the Pen to perform a stroke

Klassenbeschreibung

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
)
/* Methoden */
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)
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Stroke::getCap(): int

Shall retrieve the line cap setting of this Stroke

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Stroke::getJoin(): int

Shall retrieve the line join setting of this Stroke

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Stroke::getMiterLimit(): float

Shall retrieve the miter limit of this Stroke

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Stroke::getThickness(): float

Shall retrieve the thickness of this Stroke

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Stroke::setCap(int $cap)

Shall set the line cap setting for this Stroke

Parameter-Liste

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

Beschreibung

public UI\Draw\Stroke::setJoin(int $join)

Shall set the line join setting for this Stroke

Parameter-Liste

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Rückgabewerte

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

Beschreibung

public UI\Draw\Stroke::setMiterLimit(float $limit)

Set the miter limit for this Stroke

Parameter-Liste

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

Beschreibung

public UI\Draw\Stroke::setThickness(float $thickness)

Shall set the thickness for this Stroke

Parameter-Liste

thickness

The new thickness

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

Einführung

Represents a solid color brush

Klassenbeschreibung

class UI\Draw\Brush {
/* Constructor */
public __construct(UI\Draw\Color $color)
public __construct(int $color)
/* Methoden */
public getColor(): UI\Draw\Color
public setColor(UI\Draw\Color $color): void
public setColor(int $color): void
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Brush::getColor(): UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

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

Parameter-Liste

color

Can be a UI\Draw\Color or RRGGBBAA

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

Einführung

Abstract for gradient brushes

Klassenbeschreibung

abstract class UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Methoden */
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
/* Geerbte Methoden */
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
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Rückgabewerte

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

Beschreibung

public UI\Draw\Brush\Gradient::delStop(int $index): int

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Parameter zur Verfügung.

Parameter-Liste

index

Rückgabewerte

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

Beschreibung

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

Parameter-Liste

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

Rückgabewerte

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

Einführung

Klassenbeschreibung

class UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $end)
/* Geerbte Methoden */
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
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Brush\LinearGradient::__construct(UI\Point $start, UI\Point $end)

Shall construct a new linear gradient

Parameter-Liste

start

end

User Contributed Notes

There are no user contributed notes for this page.


Radial Gradient

(UI 2.0.0)

Einführung

Klassenbeschreibung

class UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $outer, float $radius)
/* Geerbte Methoden */
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
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Brush\RadialGradient::__construct(UI\Point $start, UI\Point $outer, float $radius)

Shall construct a new radial gradient

Parameter-Liste

start

outer

radius

User Contributed Notes

There are no user contributed notes for this page.


Represents Text Layout

(UI 0.9.9)

Einführung

A Text Layout represents the layout of text which will be drawn by the Pen

Klassenbeschreibung

class UI\Draw\Text\Layout {
/* Constructor */
public __construct(string $text, UI\Draw\Text\Font $font, float $width)
/* Methoden */
public setColor(UI\Draw\Color $color, int $start = 0, int $end = ?)
public setColor(int $color, int $start = 0, int $end = ?)
public setWidth(float $width)
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Text\Layout::__construct(string $text, UI\Draw\Text\Font $font, float $width)

Shall construct a new Text Layout

Parameter-Liste

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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Text\Layout::setWidth(float $width)

Shall set the width of this Text Layout

Parameter-Liste

width

The new width

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

Einführung

Loads a described font

Klassenbeschreibung

class UI\Draw\Text\Font {
/* Constructor */
public __construct(UI\Draw\Text\Font\Descriptor $descriptor)
/* Methoden */
public getAscent(): float
public getDescent(): float
public getLeading(): float
public getUnderlinePosition(): float
public getUnderlineThickness(): float
}

Inhaltsverzeichnis

  • 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

Beschreibung

public UI\Draw\Text\Font::__construct(UI\Draw\Text\Font\Descriptor $descriptor)

Shall construct a new Font using the given descriptor

Parameter-Liste

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

Beschreibung

public UI\Draw\Text\Font::getAscent(): float

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font::getDescent(): float

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font::getLeading(): float

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font::getUnderlinePosition(): float

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font::getUnderlineThickness(): float

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

Einführung

Describes a font

Klassenbeschreibung

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
)
/* Methoden */
public getFamily(): string
public getItalic(): int
public getSize(): float
public getStretch(): int
public getWeight(): int
}

Inhaltsverzeichnis

  • 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

Beschreibung

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

Parameter-Liste

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

Beschreibung

public UI\Draw\Text\Font\Descriptor::getFamily(): string

Shall return the requested font family

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font\Descriptor::getItalic(): int

Shall return constant setting

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font\Descriptor::getSize(): float

Shall return the requested size

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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

Beschreibung

public UI\Draw\Text\Font\Descriptor::getStretch(): int

Shall return requested stretch

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Funktionen »
  • 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

Beschreibung

public UI\Draw\Text\Font\Descriptor::getWeight(): int

Shall return requested weight

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


UI Funktionen

Inhaltsverzeichnis

  • 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 Funktionen
  • UI\quit »
  • PHP Manual
  • UI Funktionen
  • Retrieve Font Families

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

Beschreibung

UI\Draw\Text\Font\fontFamilies(): array

Returns an array of valid font families for the current system

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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 Funktionen
  • Quit UI Loop

UI\quit

(UI 2.0.0)

UI\quit — Quit UI Loop

Beschreibung

UI\quit(): void

Shall cause the main loop to be exited

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

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 Funktionen
  • Enter UI Loop

UI\run

(UI 2.0.0)

UI\run — Enter UI Loop

Beschreibung

UI\run(int $flags = ?): void

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

Parameter-Liste

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

Rückgabewerte

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

Einführung

Klassenbeschreibung

final class UI\Draw\Text\Font\Weight {
/* Konstanten */
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;
}

Vordefinierte Konstanten

UI\Draw\Text\Font\Weight::Thin
UI\Draw\Text\Font\Weight::UltraLight
UI\Draw\Text\Font\Weight::Light
UI\Draw\Text\Font\Weight::Book
UI\Draw\Text\Font\Weight::Normal
UI\Draw\Text\Font\Weight::Medium
UI\Draw\Text\Font\Weight::SemiBold
UI\Draw\Text\Font\Weight::Bold
UI\Draw\Text\Font\Weight::UltraBold
UI\Draw\Text\Font\Weight::Heavy
UI\Draw\Text\Font\Weight::UltraHeavy

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

Einführung

Klassenbeschreibung

final class UI\Draw\Text\Font\Italic {
/* Konstanten */
const int Normal = 0;
const int Oblique = 1;
const int Italic = 2;
}

Vordefinierte Konstanten

UI\Draw\Text\Font\Italic::Normal
UI\Draw\Text\Font\Italic::Oblique
UI\Draw\Text\Font\Italic::Italic

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

Einführung

Klassenbeschreibung

final class UI\Draw\Text\Font\Stretch {
/* Konstanten */
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;
}

Vordefinierte Konstanten

UI\Draw\Text\Font\Stretch::UltraCondensed
UI\Draw\Text\Font\Stretch::ExtraCondensed
UI\Draw\Text\Font\Stretch::Condensed
UI\Draw\Text\Font\Stretch::SemiCondensed
UI\Draw\Text\Font\Stretch::Normal
UI\Draw\Text\Font\Stretch::SemiExpanded
UI\Draw\Text\Font\Stretch::Expanded
UI\Draw\Text\Font\Stretch::ExtraExpanded
UI\Draw\Text\Font\Stretch::UltraExpanded

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

Einführung

Klassenbeschreibung

final class UI\Draw\Line\Cap {
/* Konstanten */
const int Flat;
const int Round;
const int Square;
}

Vordefinierte Konstanten

UI\Draw\Line\Cap::Flat
UI\Draw\Line\Cap::Round
UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

Einführung

Klassenbeschreibung

final class UI\Draw\Line\Join {
/* Konstanten */
const int Miter;
const int Round;
const int Bevel;
}

Vordefinierte Konstanten

UI\Draw\Line\Join::Miter
UI\Draw\Line\Join::Round
UI\Draw\Line\Join::Bevel

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

Einführung

Klassenbeschreibung

final class UI\Key {
/* Konstanten */
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;
}

Vordefinierte Konstanten

UI\Key::Escape
UI\Key::Insert
UI\Key::Delete
UI\Key::Home
UI\Key::End
UI\Key::PageUp
UI\Key::PageDown
UI\Key::Up
UI\Key::Down
UI\Key::Left
UI\Key::Right
UI\Key::F1
UI\Key::F2
UI\Key::F3
UI\Key::F4
UI\Key::F5
UI\Key::F6
UI\Key::F7
UI\Key::F8
UI\Key::F9
UI\Key::F10
UI\Key::F11
UI\Key::F12
UI\Key::N0
UI\Key::N1
UI\Key::N2
UI\Key::N3
UI\Key::N4
UI\Key::N5
UI\Key::N6
UI\Key::N7
UI\Key::N8
UI\Key::N9
UI\Key::NDot
UI\Key::NEnter
UI\Key::NAdd
UI\Key::NSubtract
UI\Key::NMultiply
UI\Key::NDivide

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

Einführung

Klassenbeschreibung

class UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Geerbte Eigenschaften */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Geerbte Methoden */
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)

Einführung

Klassenbeschreibung

class UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Geerbte Eigenschaften */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Geerbte Methoden */
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: Frequently Asked Questions

  • Allgemeine Informationen
  • Mailing-Listen
  • PHP beziehen
  • PHP und Datenbanken
  • Installation
  • Probleme bei der Kompilierung
  • PHP verwenden
  • Password Hashing — Sicheres Password Hashing
  • PHP und HTML
  • PHP und COM
  • Verschiedene Fragen

User Contributed Notes

There are no user contributed notes for this page.


Allgemeine Informationen

Dieses Kapitel beinhaltet allgemeine Fragen zu PHP: Was es ist und was es tut.

  1. Was ist PHP?
  2. Für was steht PHP?
  3. Wie stehen die verschiedenen PHP-Versionen zueinander?
  4. Kann ich mehrere verschiedene PHP-Versionen zur selben Zeit laufen lassen?
  5. Ich glaube, ich habe einen Bug gefunden!
Was ist PHP?

Aus dem Vorwort des Handbuches:

PHP ist die Abkürzung für "PHP: Hypertext Preprocessor", eine weitverbreitete Open Source Skriptsprache speziell für Webentwicklungen. PHP läßt sich in HTML einbinden. Seine Syntax erinnert an C, Java und Perl und es ist einfach zu erlernen. Das Hauptziel dieser Sprache ist es, Webentwicklern die Möglichkeit zu geben, schnell dynamisch generierte Webseiten zu erzeugen.

Für was steht PHP?

PHP steht für PHP: Hypertext Preprocessor. Das verwirrt einige Menschen, da das erste Wort der Abkürzung die Abkürzung ist. Dieser Typ von Abkürzung wird rekursive Abkürzung genannt. Wer sich weiter für das Thema der rekursiven Abkürzungen interessiert, findet im » Free On-Line Dictionary of Computing oder der » Wikipedia. weitere Informationen dazu.

Wie stehen die verschiedenen PHP-Versionen zueinander?

PHP/FI 2.0 ist eine frühe und nicht mehr unterstützte Version von PHP. PHP 3 ist der Nachfolger von PHP/FI 2.0 und wesentlich besser. PHP 8 ist die aktuelle Generation von PHP, die die Zend Engine 4 als Sprachkern, die neben weiteren Verbesserungen eine deutlich verbesserte Objektorientierung bietet.

Kann ich mehrere verschiedene PHP-Versionen zur selben Zeit laufen lassen?

Ja. Weitere Informationen dazu finden sich in der Datei INSTALL, die der Source-Distribution von PHP beiliegt.

Ich glaube, ich habe einen Bug gefunden!

Sie sollten die PHP Bug-Datenbank aufrufen und herausfinden, ob es sich bei dem Bug um einen bereits bekannten Bug handelt. Ist der Bug noch nicht bekannt, können Sie diesen über das Reportformular posten. Wenn Sie das Reportformular verwenden, bekommt ihr Bug automatisch eine Nummer zugewiesen, so das Sie später wiederkehren und Anhand der Nummer herausfinden können, ob der Bug gefixed wurde. Die Bug-Datenbank ist unter » https://github.com/php/php-src/issues zu finden.

User Contributed Notes

There are no user contributed notes for this page.


Mailing-Listen

In dieser Rubrik finden Sie Informationen, wie Sie mit der PHP-Community in Kontakt treten können. Wir empfehlen Ihnen die Mailing-Listen.

  1. Gibt es PHP-Mailing-Listen?
  2. Gibt es auch andere Communities?
  3. Kann ich meine eigene PHP-Mailing-Liste starten?
  4. Hilfe! Ich kann eine der Mailing-Listen nicht abonnieren / abbestellen!
  5. Gibt es ein Archiv der Mailing-Listen?
  6. Was kann ich die Mailing-Listen fragen?
  7. Welche Informationen soll ich mitschicken, wenn ich an die Mailing-Liste schreibe?
Gibt es PHP-Mailing-Listen?

Natürlich! Es gibt eine ganze Reihe von Mailing-Listen für verschiedene Themen. Die wichtigsten Community-Mailing-Listen finden Sie auf unserer » Mailing-Listen-Seite.

Die allgemeinste Mailing-Liste ist php-general. Um diese Liste zu abonnieren, schicken Sie eine leere E-Mail an » php-general+subscribe@lists.php.net. Um die Liste abzubestellen, schicken Sie eine leere E-Mail an » php-general+unsubscribe@lists.php.net.

Sie können die Listen auch über das Web-Interface auf unserer » Mailing-Listen-Seite abonnieren oder abbestellen. Abmeldehinweise finden Sie auch im Fuß jeder Mailimg-Listen-Nachricht.

Gibt es auch andere Communities?

Auf der ganzen Welt gibt es unzählige Communities, die sich mit PHP beschäftigen. Links zu solchen Ressourcen (und weitergehende Informationen) finden Sie auf unserer » Support-Seite.

Kann ich meine eigene PHP-Mailing-Liste starten?

Ja. Genauer gesagt: Wir erlauben es nicht nur, wir unterstützen es sogar! Anderen durch das eigene Wissen und die eigene Erfahrung mit PHP zu helfen, hilft, das Wachstum und die Entwicklung der globalen PHP-Community und der Sprache selbst zu beschleunigen.

Hilfe! Ich kann eine der Mailing-Listen nicht abonnieren / abbestellen!

Der häufigste Grund für Probleme bei der Abmeldung von unseren Mailing-Listen ist die Nutzung von E-Mail-Weiterleitungen. Wenn Ihre E-Mail-Adresse z. B. elephpant@example.com ist, Sie sich aber mit der Weiterleitung php-lists@example.com an der Mailing-Liste angemeldet haben und Sie diese Adresse an elephpant@example.com weiterleiten, so wird der Versuch, sich mit elephpant@example.com abzumelden, scheitern, da diese Adresse unserem System nicht bekannt ist. Stattdessen müssen Sie die Adresse abmelden, an die die E-Mail gesendet wird, indem Sie eine E-Mail von dieser Adresse senden - in diesem Fall also von php-lists@example.com.

Gibt es ein Archiv der Mailing-Listen?

Ja, Sie finden eine Liste zu einigen Archiv-Seiten auf unserer » Mailing-Listen-Seite. Sie finden außerdem dutzende Seiten, die den Inhalt unserer Mailing-Liste archivieren und/oder syndizieren, indem Sie Ihre favorisierte Internet-Suchmaschine nutzen und nach "php mailing list archives" suchen.

Alle Mailing-Listen-Artikel werden auch als News-Postings archiviert. Den News-Server können Sie mit einem Newsreader unter » news://news.php.net/ erreichen. Es gibt auch ein experimentelles Web-Interface für den Newsserver unter » http://news.php.net/.

Was kann ich die Mailing-Listen fragen?

PHP wird immer umfangreicher und beliebter. Aus diesem Grund kann der Verkehr auf der php-general-Mailing-Liste sehr hoch sein. Zur Zeit werden täglich zwischen 75 und 200 Artikel versendet, manchmal sogar noch mehr. Daher ist es in jedermanns Sinn, wenn Sie die Liste nur dann nutzen, wenn Sie nirgendwo eine Antwort auf Ihre Frage gefunden haben.

Bevor Sie an die Liste schreiben, schauen Sie bitte in diese FAQ und das Handbuch, ob Sie dort vielleicht schon die gesuchte Antwort finden. Falls Sie dort nicht fündig werden, schauen Sie bitte in die Archive der Mailing-Listen (siehe oben). Wenn Sie Probleme mit der Installation oder Konfiguration von PHP haben, stellen Sie bitte sicher, dass Sie die mitgelieferte Dokumentation und die READMEs gelesen haben. Wenn Sie jetzt immer noch keine Antwort gefunden haben, können Sie Ihre Frage gerne an die passende Mailing-Liste schicken.

Um sicherzustellen, dass Sie die besten Antworten erhalten (und um die Wahrscheinlichkeit zu senken, dass Sie die anderen Entwickler frustrieren), prüfen Sie bitte, ob Sie Ihre Frage an die passende Mailing-Liste schicken. Wenn Sie z. B. Probleme mit der Installation von PHP haben, sollten Sie Ihre Frage an die php-install-Mailing-Liste schicken. Eine Warnung: Einige Listen haben ähnliche Name, aber komplett unterschiedliche Nutzungen; eine Frage zu PHP-Skripten unter Windows sollte an die Windows-PHP-Nutzer-Liste, aber nicht an die Windows-Internals-Liste geschickt werden.

Bevor Sie eine Frage stellen, schauen Sie sich bitte die Seite » How To Ask Questions The Smart Way an.

Welche Informationen soll ich mitschicken, wenn ich an die Mailing-Liste schreibe?

E-Mails wie "Hilfe, ich schaffe es nicht, PHP ans Laufen zu bekommen. Was habe ich falsch gemacht?" sollten unbedingt vermieden werden. Wenn Sie solche Probleme haben, müssen Sie das benutzte Betriebssystem und die PHP-Version, die Sie zu benutzen versuchen, sowie, wie Sie PHP erhalten haben (vorkompiliert, Git, RPMs etc.), angeben. Außerdem sollten Sie angeben, was Sie bisher schon versucht haben und welche Fehlermeldung sie erhalten haben.

Dies gilt auch für alle anderen Probleme. Sie müssen immer angeben, was Sie getan haben und was Sie zu tun versuchen. Außerdem müssen Sie alle erhaltenen Fehlermeldungen angeben. Wenn Sie Probleme mit Ihren Quelltexten haben, müssen Sie den Teil, der nicht funktioniert, mitschicken. Allerdings sollten Sie auch nicht mehr Code als nötig mitschicken! Dadurch würde Ihre E-Mail schlecht lesbar und viele Leute könnten Ihre Frage deswegen ignorieren. Falls Sie sich unsicher sind, wie viele Informationen Sie schicken sollen, schicken Sie so viel, wie Ihrer Meinung nach relevant für das aktuelle Problem relevant ist. Ggf. sollten Sie nach Anforderung weitere Informationen schicken.

Ein weiterer wichtiger Punkt ist auch, dass Sie Ihr Problem in der Betreff-Zeile zusammenfassen. Ein Betreff wie "Hilfe!" oder "Was ist das Problem hier?" wird mit Sicherheit von einem Großteil der Leser ignoriert werden.

Außerdem bitten wir Sie, die Seite » How To Ask Questions The Smart Way zu lesen, da dies auch für Sie selbst eine große Hilfe sein kann.

User Contributed Notes

There are no user contributed notes for this page.


PHP beziehen

Diese Rubrik behandelt Downloadmöglichkeiten für die verschiedenen Betriebssysteme.

  1. Woher kann ich PHP beziehen?
  2. Sind kompilierte Binärversionen verfügbar?
  3. Woher bekommen ich die Bibliotheken, die benötigt werden, um einige der optionalen PHP-Erweiterungen zu kompilieren?
  4. Wie bekomme ich diese Bibliotheken zum Laufen?
  5. Ich habe die aktuellste Version des PHP-Quellcodes vom Git-Repository heruntergeladen. Was benötige ich jetzt, um PHP auf meinem Windowssystem zu kompilieren?
  6. Wo finde ich eine Browser Capabilities Datei?
  7. Was bedeutet "thread safety" beim Herunterladen von PHP?
Woher kann ich PHP beziehen?

Sie können PHP von jedem der Mitglieder des PHP-Netzwerks herunteraden. Diese finden Sie unter » https://www.php.net/. Sie können weiterhin mittels anonymem Git die allerneuste Version des Quellcodes herunterladen. Für weitere Informationen besuchen Sie diese Seite: » https://www.php.net/git.php.

Sind kompilierte Binärversionen verfügbar?

Wir bieten nur Binärversionen für Windowssysteme an, da wir PHP nicht für jede größere Linux/Unix-Plattform mit jeder vorstellbaren Kombination an Erweiterungen kompilieren können. Bitte beachten Sie auch, dass viele Linux-Distributionen heutzutage schon PHP integriert haben. Windows Binärdateien können von unserer » Downloadseite heruntergeladen werden, passende Linux-Binärversionen finden Sie auf der Webseite Ihrer Distribution.

Woher bekommen ich die Bibliotheken, die benötigt werden, um einige der optionalen PHP-Erweiterungen zu kompilieren?

Hinweis: Die mit einem * markierten Bibliotheken sind nach unserem Wissen nicht threadsicher; ihre Verwendung wird in einer multi-threaded Umgebung nicht empfohlen.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK
  • » free LDAP server.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Available locally.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

Wie bekomme ich diese Bibliotheken zum Laufen?

Sie sollten den Anweisungen, die mit der Bibliothek mitgeliefert werden, folgen. Manche dieser Bibliotheken (z.B. die GD Bibliothek) werden automatisch erkannt, wenn Sie das PHP 'configure'-Script ausführen. Andere müssen Sie mittels der '--with-EXTENSION'-Option von 'configure' aktivieren. 'configure --help' liefert Ihnen eine Auflistung.

Ich habe die aktuellste Version des PHP-Quellcodes vom Git-Repository heruntergeladen. Was benötige ich jetzt, um PHP auf meinem Windowssystem zu kompilieren?

Die aktuelle Anleitung ist im PHP Wiki zu finden: » Step by Step Build Instructions

Wo finde ich eine Browser Capabilities Datei?

Sie finden eine browscap.ini Datei unter » http://browscap.org/.

Was bedeutet "thread safety" beim Herunterladen von PHP?

Thread-Sicherheit bedeutet, dass PHP in einer einer Multithread-Webserver Umgebung wie z.B. Apache2 unter Windows funktioniert. Thread-Sicherheit funktioniert, indem eine lokale Kopie des Speichers in jedem Thread angelegt wird, so dass die Daten nicht mit anderen Threads kollidieren.

Was muss ich wählen? Wenn Sie PHP als CGI-Version ausführen wollen, dann benötigen Sie keine Thread-Sicherheit, da die Binärdatei bei jeder Anfrage aufgerufen wird. Für Multithread-Webserver, wie z.B. IIS5 und IIS6 sollten Sie die threadsichere Version von PHP nutzen.

User Contributed Notes

There are no user contributed notes for this page.


PHP und Datenbanken

Dieser Abschnitt enthält häufige Fragen über die Verbindung von PHP und Datenbanken. PHP kann in der Tat auf praktisch jede verfügbare Datenbank zugreifen.

  1. Ich habe gehört, dass es möglich ist, den Microsoft SQL-Server aus PHP anzusprechen. Wie?
  2. Kann ich auf Microsoft Access-Datenbanken zugreifen?
Ich habe gehört, dass es möglich ist, den Microsoft SQL-Server aus PHP anzusprechen. Wie?

Auf Unix-Rechnern können Sie PDO_ODBC oder die Unified ODBC API verwenden.

Auf Windows-Rechnern können Sie ebenfalls PDO_SQLSRV oder SQLSRV verwenden.

Sehen Sie sich auch die Antwort auf die nächste Frage an.

Kann ich auf Microsoft Access-Datenbanken zugreifen?

Wenn Sie PHP auf einem Unix-Rechner betreiben und auf MS Access auf einem Windows-Rechner zugreifen wollen, brauchen sie ODBC-Treiber für Unix. » OpenLink Software bietet Unix-basierte ODBC-Treiber an, die dazu geeignet sind.

Eine weitere Alternative ist es, einen SQL-Server zu benutzen, der ODBC-Treiber für Windows anbietet und diesen dann zu benutzen, um die Daten dort abzulegen, um sie dann von Microsoft Access (über ODBC) und PHP (mit den mitgelieferten Treibern) aus anzusprechen, oder ein dazwischengeschaltetetes Dateiformat zu benutzen, das sowohl Access als auch PHP verstehen, beispielsweise Plaintext oder dBase-Datenbanken. Zu diesem Punkt schreibt Tim Hayes von OpenLink Software:

Eine andere Datenbank als vermittelndes Element zu benutzen ist keine gute Idee, wenn Sie ODBC direkt von PHP aus zur Datenbank benutzen können - etwa mit den Openlink-Treibern. Wenn Sie wirklich ein zwischengeschaltetes Dateiformat benötigen, hat Openlink jetzt Virtuoso (eine virtuelle Datenbank) für NT, Linux und andere Unix-Plattformen herausgebracht. Bitte besuchen Sie unsere » Webseite, wenn Sie Virtuoso kostenlos herunterladen wollen.

Eine Möglichkeit, die sich als erfolgreich herausgestellt hat, ist die Benutzung von MySQL und den MyODBC-Treibern unter Windows, um die Datenbanken zu synchronisieren. Steve Lawrence schreibt dazu:

  • Installieren Sie MySQL wie in der Dokumentation beschrieben auf ihrem System. Die neueste Version finden Sie auf » www.mysql.com Es ist keine spezielle Konfiguration nötig, außer dass Sie beim Erzeugen einer Datenbank und der Einrichtung des Benutzeraccounts im Host-Feld ein % oder den Hostnamen des Windows-Computers, von dem aus Sie zugreifen möchten, eintragen sollten. Notieren Sie sich den Servernamen, Benutzernamen und das Passwort.
  • Laden Sie die MyODBC for Windows-Treiber von der MySQL-Seite herunter. Installieren Sie ihn auf ihrem Windows-Rechner. Sie können die Funktionsfähigkeit mit den mitgelieferten Programmen testen.
  • Erstellen Sie eine Benutzer- oder System-DSN in den ODBC-Optionen in der Systemsteuerung. Überlegen Sie sich einen DSN-Namen und geben Sie den Hostnamen, Benutzernamen, Passwort, Port, etc ihrer MySQL-Datenbank an, die Sie im 1. Schritt konfiguriert haben.
  • Installieren Sie Access als Vollinstallation. Das stellt sicher, dass Sie die richtigen Add-Ins haben. Zumindest benötigen Sie die ODBC-Unterstützung und den Linked-Table-Manager.
  • Jetzt zum lustigen Teil! Erstellen Sie eine neue Access-Datenbank. Rechtsklicken Sie im Tabellenfenster und wählen Sie Link Tables/Tabellen verknüpfen oder im Menü Datei den Punkt Get External Data und dann Link Tables/Tabellen verknüpfen. Wenn das Dateibrowser-Fenster erscheint, wählen Sie Dateien vom Typ: ODBC. Wählen Sie System-DSN und den Namen der DSN, die Sie in Schritt 3 erstellt haben. Wählen sie die zu verknüpfende Tabelle, klicken Sie auf OK und Sie können jetzt die Tabelle öffnen und Daten auf Ihrem MySQL-Server hinzufügen/löschen/ändern. Sie können auch Abfragen erzeugen, Tabellen importieren und exportieren und Formulare und Reports generieren, etc.

Tipps und Tricks:

  • Sie können Ihre Tabellen in Access erstellen und nach MySQL exportieren und Sie dann wieder verknüpfen. Das erleichtert das Erstellen von Tabellen.
  • Wenn Sie Tabellen in Access erstellen, müssen Sie einen Primärschlüssel definieren, wenn Sie über Access Schreibzugriff haben wollen. Vergewissern Sie sich, dass sie einen Primärschlüssel in MySQL erzeugen, bevor Sie die Tabelle in Access verknüpfen.
  • Wenn Sie ein Tabelle in MySQL ändern, müssen Sie sie in Access neu verknüpfen. Rufen Sie Tools>add-ins>linked table manager auf, suchen Sie ihre ODBC-DSN, und wählen Sie die Tabelle aus, die neu verknüpft werden soll. Sie können Ihre DSN-Quelle auch verschieben, wenn Sie die "always prompt for new location"-Checkbox ankreuzen, bevor Sie OK klicken.

User Contributed Notes

knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.


Installation

In diesem Abschnitt geht es um übliche Fragen zur Installation von PHP. PHP gibt es für fast jedes Betriebssystem und fast jeden Webserver.

Um PHP zu installieren, folgen Sie bitte den Anweisungen im Installation und Konfiguration.

  1. Warum sollte ich Apache2 mit threaded MPM nicht in einer Produktionsumgebung verwenden?
  2. Unix/Windows: Wo sollte sich meine php.ini befinden?
  3. Unix: Ich habe PHP installiert, aber jedesmal, wenn ich eine Seite aufrufe, bekomme ich die Meldung 'Document Contains No Data'! Woran liegt das?
  4. Unix: Ich habe PHP mit RPM-Paketen installiert, aber Apache verarbeitet die PHP-Seiten nicht. Was ist da los?
  5. Unix: Ich habe Apache mit dem FrontPage-Erweiterungs-Patch versehen und plötzlich funktioniert PHP nicht mehr. Ist PHP zur FrontPage-Erweiterung für Apache inkompatibel?
  6. Unix/Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich eine leere Seite.
  7. Unix/Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich vom Server einen 500 Fehler.
  8. Manche Betriebssysteme: Ich habe PHP ohne Fehlermeldungen installiert, aber wenn ich versuche, Apache zu starten, erhalte ich Fehler wegen undefinierter Symbole: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich die Fehlermeldung: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: Ich habe alle Anweisungen befolgt, aber ich erreiche keine Zusammenarbeit zwischen PHP und den IIS.
  11. Wenn Ich PHP mit IIS, PWS, OmniHTTPD oder Xitami als CGI laufen lasse, bekomme ich die folgende Fehlermeldung: Security Alert! PHP CGI cannot be accessed directly..
  12. Wie kann ich herausfinden, ob meine php.ini gefunden und gelesen wird? Anscheinend ist das nicht der Fall, weil meine Änderungen nicht übernommen werden.
  13. Wie füge ich unter Windows mein PHP-Verzeichnis zu PATH hinzu?
  14. Wie mache ich unter Windows die Datei php.ini für PHP verfügbar?
  15. Ist es möglich, die Apache Content-Negotiation (MultiViews Option) mit PHP zu verwenden?
  16. Ist PHP auf die Bearbeitung von Anfragen mit der GET- und POST-Methode beschränkt?
Warum sollte ich Apache2 mit threaded MPM nicht in einer Produktionsumgebung verwenden?

PHP ist Klebstoff. Es ist der Klebstoff, der verwendet wird, um coole Web-Anwendungen zu erstellen, indem er dutzende von Bibliotheken von Drittanbietern zusammenklebt und sie über eine intuitiv und einfach erlernbare Schnittstelle als zusammenhängende Einheit erscheinen lässt. Die Flexibilität und die Mächtigkeit von PHP sind auf die Stabilität und Robustheit der zugrunde liegenden Plattform angewiesen. Es braucht ein funktionierendes Betriebssystem, einen funktionierenden Webserver und funktionierende Bibliotheken Dritter, um zusammenzukleben. Wenn eines davon nicht mehr funktioniert, braucht PHP Wege, um die Probleme erkennen und schnell beheben zu können. Wenn Sie das zugrunde liegende Gerüst dadurch komplexer machen, dass Sie keine völlig voneinander getrennten Ausführungsthreads und Speichersegmente und keine starke Sandbox für jede einzelne Anfrage haben, lassen Sie weitere Schwachstellen ins System von PHP einfließen.

Falls Sie threaded MPM benutzen wollen, sollten Sie nach einer FastCGI-Konfiguration schauen, in der PHP in seinem eigenen Speicherbereich läuft.

Unix/Windows: Wo sollte sich meine php.ini befinden?

Unter Unix sollte sie standardmäßig in /usr/local/lib sein, was <install-path>/lib ist. Die Meisten werden das beim Übersetzen mit der Option --with-config-file-path ändern wollen. Sie können das z. B. mit

--with-config-file-path=/etc
festlegen. Dann kopieren Sie die php.ini-development der Distribution nach /etc/php.ini und editieren sie, um alle gewünschten lokalen Änderungen vorzunehmen.

--with-config-file-scan-dir=PATH

Unter Windows ist der standardmäßige Pfad für die php.ini das Windows-Verzeichnis. Falls die den Apache Webserver verwenden, wird die php.ini zuerst im Apache-Installationsverzeichnis, z. B. c:\program files\apache group\apache, gesucht. Dadurch können Sie auf demselben Rechner verschiedene php.ini-Dateien für verschiedene Apache-Versionen haben.

Siehe auch das Kapitel über die Konfigurationsdatei.

Unix: Ich habe PHP installiert, aber jedesmal, wenn ich eine Seite aufrufe, bekomme ich die Meldung 'Document Contains No Data'! Woran liegt das?

Das bedeutet wahrscheinlich, dass PHP irgend ein Problem hat und einen Core Dump (Speicherauszug) erzeugt. Schauen Sie in der Fehler-Logdatei Ihres Servers nach, ob das der Fall ist, und versuchen Sie dann, das Problem mit einem kleinen Test-Skript zu reproduzieren. Falls Sie sich mit 'gdb' auskennen, ist es für die Entwickler beim Lokalisieren des Problems sehr hilfreich, wenn Sie Ihrem Fehlerbericht einen Backtrace hinzufügen. Falls Sie PHP als Apache-Modul verwenden, können Sie in etwa Folgendes versuchen:

  • Stoppen Sie Ihre httpd-Prozesse

  • gdb httpd

  • Stoppen Sie Ihre httpd-Prozesse

  • > run -X -f /pfad/zur/httpd.conf

  • Rufen Sie mit Ihrem Browser die URL auf, die das Problem verursacht

  • > run -X -f /path/to/httpd.conf

  • gdb sollte Sie jetzt darüber in Kenntnis setzen, falls Sie einen Core Dump bekommen

  • Geben Sie ein: bt

  • Sie sollten Ihren Backtrace in Ihren Fehlerbericht einfügen und diesen unter » https://github.com/php/php-src/issues abgeben.

Falls Sie in Ihrem Skript Funktionen regulärer Ausdrücke (preg_match() und Freunde) verwenden, sollten Sie sicherstellen, dass Sie PHP und Apache mit demselben Programmpaket für reguläre Ausdrücke übersetzt haben. Mit PHP und Apache 1.3.x sollte das automatisch der Fall sein.

Unix: Ich habe PHP mit RPM-Paketen installiert, aber Apache verarbeitet die PHP-Seiten nicht. Was ist da los?

Unter der Annahme, dass Sie sowohl Apache als auch PHP mit RPM-Paketen installiert haben, müssen Sie einige oder alle der folgenden Zeilen in die Datei httpd.conf einfügen oder die Kommentarzeichen davor entfernen:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
Und fügen Sie
AddType application/x-httpd-php .php
... in die globalen Eigenschaften oder in die Eigenschaften der VirtualDomain, für die Sie PHP-Unterstützung benötigen, ein.

Unix: Ich habe Apache mit dem FrontPage-Erweiterungs-Patch versehen und plötzlich funktioniert PHP nicht mehr. Ist PHP zur FrontPage-Erweiterung für Apache inkompatibel?

Nein, PHP funktioniert bestens mit der FrontPage-Erweiterung. Das Problem liegt darin, dass der FrontPage-Patch mehrere Apache-Strukturen verändert, auf die sich PHP verlässt. Eine Neuübersetzung von PHP (mittels 'make clean ; make'), nachdem der Patch angewandt wurde, löst das Problem.

Unix/Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich eine leere Seite.

Wenn Sie sich im Browser den Quelltext der Seite anschauen, werden Sie vermutlich den Quellcode Ihres PHP-Skripts sehen können. Das bedeutet, dass der Webserver das Skript nicht zur Interpretation an PHP übergeben hat. Mit Ihrer Server-Konfiguration ist etwas nicht in Ordnung - überprüfen Sie Ihre Server-Konfiguration nochmal genau anhand der PHP-Installationsanleitung.

Unix/Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich vom Server einen 500 Fehler.

Beim Versuch des Servers PHP zu starten ist etwas schiefgegangen. Wechseln Sie auf der Kommandozeile (in der Eingabeaufforderung) in das Verzeichnis, das die ausführbare PHP-Datei (unter Windows php.exe) enthält und lassen Sie php -i laufen, um eine sinnvolle Fehlermeldung zu bekommen. Falls PHP irgendwelche Probleme bei der Ausführung hat, werden entsprechende Fehlermeldungen ausgegeben, die Ihnen Hinweise darauf liefern, was zu tun ist. Falls sich der Bildschirm mit HTML-Quelltext füllt (die Ausgabe der Funktion phpinfo()), funktioniert PHP und Ihr Problem könnte mit Ihrer Server-Konfiguration zusammenhängen, die Sie dann nochmal genau überprüfen sollten.

Manche Betriebssysteme: Ich habe PHP ohne Fehlermeldungen installiert, aber wenn ich versuche, Apache zu starten, erhalte ich Fehler wegen undefinierter Symbole:
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

Das hat nichts mit PHP zu tun, sondern mit den MySQL-Client-Bibliotheken. Manche benötigen --with-zlib, manche nicht. Auf diese Frage wird in den MySQL-FAQ eingegangen.

Windows: Ich habe PHP installiert, aber wenn ich versuche, mit meinem Browser ein PHP-Skript aufzurufen, erhalte ich die Fehlermeldung:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Diese Fehlermeldung bedeutet, dass PHP daran gescheitert ist, überhaupt irgendwas auszugeben. Wechseln Sie auf der Kommandozeile (in der Eingabeaufforderung) in das Verzeichnis, das die ausführbare PHP-Datei (unter Windows php.exe) enthält und lassen Sie php -i laufen, um eine sinnvolle Fehlermeldung zu bekommen. Falls PHP irgendwelche Probleme bei der Ausführung hat, werden entsprechende Fehlermeldungen ausgegeben, die Ihnen Hinweise darauf liefern, was zu tun ist. Falls sich der Bildschirm mit HTML-Quelltext füllt (die Ausgabe der Funktion phpinfo()), funktioniert PHP.

Funktioniert PHP erst mal auf der Kommandozeile, versuchen Sie nochmal, das Skript mit dem Browser aufzurufen. Falls das immer noch misslingt, könnte das eine der folgenden Ursachen haben:

  • Die Zugriffsberechtigungen Ihres PHP-Skripts, Ihrer php.exe, php5ts.dll, php.ini oder irgendeiner PHP-Erweiterung, die Sie versuchen zu laden, sind für den anonymen Internetbenutzer ISUR_<machinename> nicht ausreichend.
  • Die Skriptdatei existiert nicht (oder ist vielleicht, bezogen auf Ihr Web-Wurzelverzeichnis, nicht da, wo Sie denken). Beachten Sie, dass Sie beim IIS diesen Fehler aufspüren können, wenn Sie im Internet Services Manager beim Einstellen der script mappings die Option 'check file exists' ankreuzen. Falls dann eine Skriptdatei nicht existiert, gibt der Server stattdessen einen 404 Fehler zurück. Das hat außerdem den zusätzlichen Vorteil, dass der IIS die erforderlichen Authentisierungen an Ihrem Skript auf Grundlage der NTLanMan-Berechtigungen für Sie durchführt.
Windows: Ich habe alle Anweisungen befolgt, aber ich erreiche keine Zusammenarbeit zwischen PHP und den IIS.

Stellen Sie sicher, dass jeder Benutzer, der ein PHP-Skript ausführt, die Berechtigung hat php.exe auzuführen! Der IIS verwendet den Benutzer anonymous, der bei der Installation des IIS hinzugefügt wird. Dieser Benutzer benötigt die entsprechenden Berechtigungen für php.exe. Außerdem benötigt auch jeder angemeldete Benutzer die Berechtigung, php.exe auszuführen. Dem IIS4 müssen Sie mitteilen, dass PHP eine Skript-Engine ist. Lesen Sie auch diese FAQ.

Wenn Ich PHP mit IIS, PWS, OmniHTTPD oder Xitami als CGI laufen lasse, bekomme ich die folgende Fehlermeldung: Security Alert! PHP CGI cannot be accessed directly..

Sie müssen die cgi.force_redirect-Anweisung auf 0 setzen. Weil diese Anweisung standardmäßig auf 1 gesetzt ist, müssen Sie darauf achten, dass sie nicht mit einem ; auskommentiert ist. Wie alle Anweisungen wird auch diese in der php.ini gesetzt.

Wegen des standardmäßigen Werts von 1 ist es äußerst wichtig sicherzustellen, dass die richtige php.ini gelesen wird. Lesen Sie für Einzelheiten diese FAQ.

Wie kann ich herausfinden, ob meine php.ini gefunden und gelesen wird? Anscheinend ist das nicht der Fall, weil meine Änderungen nicht übernommen werden.

Rufen Sie phpinfo() auf, um zu überprüfen, ob Ihre php.ini von PHP gelesen wird. Fast ganz oben gibt es einen Punkt namens Configuration File (php.ini). Dort können Sie feststellen, wo PHP nach der php.ini sucht und ob sie gelesen wird oder nicht. Falls es dort nur einen VerzeichnisPFAD gibt, wird sie nicht gelesen und Sie sollten Ihre php.ini in dieses Verzeichnis legen. Falls der Pfad die php.ini beinhaltet, dann wird sie auch gelesen.

Wenn Ihre php.ini gelesen wird und Sie PHP als Modul verwenden, müssen Sie Ihren Webserver neu starten, nachdem Sie Änderungen an der php.ini vorgenommen haben.

Siehe auch php_ini_loaded_file().

Wie füge ich unter Windows mein PHP-Verzeichnis zu PATH hinzu?

Unter Windows:

  • Gehen Sie in die Systemsteuerung und öffnen Sie das System-Icon (Start ? Systemsteuerung)

  • Gehen Sie zum Register 'Erweitert'

  • Klicken Sie auf den Button 'Umgebungsvariablen'

  • Schauen Sie in das Fenster 'Systemvariablen'

  • Suchen Sie nach dem Pfad-Eintrag PATH (Sie müssen evtl. blättern, um ihn zu finden)

  • Doppelklicken Sie auf den Pfad-Eintrag

  • Geben Sie Ihr PHP-Verzeichnis mit vorangestelltem ';' am Ende ein (z. B. ;C:\php)

  • Drücken Sie auf OK

Hinweis: Führen Sie einen Neustart durch, nachdem Sie die obigen Schritte befolgt haben, um sicher zu stellen, dass die PATH-Änderungen übernommen werden.

Wie mache ich unter Windows die Datei php.ini für PHP verfügbar?

Es gibt mehrere Möglichkeiten, das zu erreichen. Falls Sie Apache verwenden, sehen Sie in der Apache-Dokumentation nach, andernfalls müssen Sie die Umgebungsvariable PHPRC setzen.

Ist es möglich, die Apache Content-Negotiation (MultiViews Option) mit PHP zu verwenden?

Falls Links zu PHP-Dateien die Erweiterung enthalten, funktioniert alles perfekt. Diese FAQ ist nur für den Fall, dass Links zu PHP-Dateien keine Erweiterung enthalten und Sie die Content-Negotiation verwenden wollen, um PHP-Dateien von einer URL ohne diese Erweiterung zu wählen. Ersetzen Sie in diesem Fall die Zeile AddType application/x-httpd-php .php durch:

AddHandler php5-script php
AddType text/html php
Diese Lösung funktioniert nicht mit Apache 1, da das PHP-Modul kein php-Skript erfasst.

Ist PHP auf die Bearbeitung von Anfragen mit der GET- und POST-Methode beschränkt?

Nein, es ist möglich, jede Anfragemethode zu bearbeiten, z. B. auch CONNECT. Ein korrekter Antwortstatus kann mit header() gesendet werden. Falls nur die Methoden GET und POST bearbeitet werden sollen, kann das mit dieser Apache-Konfiguration erreicht werden:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

User Contributed Notes

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/
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
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.
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)


Probleme bei der Kompilierung

Diese Sektion behandelt die meistverbreiteten Fehler, die beim Kompilieren von PHP auftauchen.

  1. Ich habe mir die aktuelle Version von PHP mit Hilfe des anonymen Git-Dienstes besorgt, kann aber kein configure-Skript finden.
  2. Ich habe Probleme PHP für den Apache zu konfigurieren. Er beschwert sich, dass er die Datei httpd.h nicht finden kann, obwohl sie sich genau dort befindet, wo ich es angegeben habe.
  3. Sie werden während des Konfigurierens von PHP (./configure), mit einem Fehler wie dem Folgenden konfrontiert: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. Warum bekomme ich folgende Meldung, wenn ich versuche Apache zu starten? fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. Wenn ich configure ausführe, bekomme ich die Fehlermeldung, dass die include-Dateien oder die GD-, gdbm- oder andere etc. Bibliotheken nicht gefunden werden konnten.
  6. Wenn die Datei language-parser.tab.c kompiliert wird, erscheinen Fehler mit der Meldung yytname undeclared.
  7. Wenn ich make ausführe, scheint alles normal zu verlaufen, aber sobald es versucht, die Applikation zu linken, beschwert es sich, einige Dateien nicht finden zu können.
  8. Wenn PHP gelinkt wird, beschwert es sich über undefinierte Referenzen.
  9. Ich habe die Schritte, die zur Installation des Apache-Moduls unter Unix nötig sind, befolgt, aber meine PHP-Skripte sind im Browser zu sehen oder ich werde aufgefordert, die Dateien zu speichern.
  10. Es heißt, es muss --activate-module=src/modules/php4/libphp4.a benutzt werden, aber diese Datei existiert nicht, also habe ich es zu --activate-module=src/modules/php4/libmodphp4.a geändert, aber es funktioniert nicht.
  11. Wenn ich versuche, Apache mit PHP als statisches Modul mittels --activate-module=src/modules/php4/libphp4.a zu kompilieren, kommt die Fehlermeldung, mein kompiler sei nicht ANSI-konform.
  12. Wenn ich versuche, PHP mittels der Option --with-apxs zu kompilieren, bekomme ich komische Fehlermeldungen.
  13. Während make bekomme ich Fehler in microtime und jede Menge RUSAGE_-Zeugs.
  14. Beim Kompilieren von PHP mit MySQL läuft configure zwar ohne Probleme, aber beim Ausführen von make bekomme ich einen Fehler wie den Folgenden: 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' Was habe ich falsch gemacht?
  15. Ich möchte mein PHP aktualisieren. Wo kann ich die ./configure-Zeile finden, die von meiner aktuellen PHP-Version verwendet wird?
  16. Wenn ich PHP mit der GD-Bibliothek kompiliere, tauchen seltsame Kompilerfehler auf oder PHP startet nicht (Segfault).
  17. Wenn ich PHP kompiliere habe ich den Eindruck zufällige Fehler zu bekommen. Ich verwende Solaris.
Ich habe mir die aktuelle Version von PHP mit Hilfe des anonymen Git-Dienstes besorgt, kann aber kein configure-Skript finden.

Sie müssen das GNU autoconf-Paket installiert haben, damit das Konfigurationsskript aus configure.in generiert werden kann. Führen Sie ./buildconf im Hauptverzeichnis der vom Git-Server geladenen Quellen aus, wird das configure-Skript generiert. (Solange Sie configure nicht mit der --enable-maintainer-mode-Option aufrufen, wird das Konfigurationsskript nicht neu erstellt, wenn die configure.in-Datei aktualisiert wird. Es sollte also darauf geachtet werden, dass das configure-Skript manuell neu generiert wird, wenn Sie feststellen, dass configure.in verändert wurde. Ein Symptom für eine solche Veränderung ist, wenn Dinge wie @VARIABLE@ im Makefile auftachen, nachdem configure oder config.status ausgeführt wurde.)

Ich habe Probleme PHP für den Apache zu konfigurieren. Er beschwert sich, dass er die Datei httpd.h nicht finden kann, obwohl sie sich genau dort befindet, wo ich es angegeben habe.

Sie müssen dem configure/setup-Skript den Top-Level-Pfad des Apache-Quellbaums mitteilen. Das bedeutet, dass z.B. --with-apache=/path/to/apache anstatt --with-apache=/path/to/apache/src angegeben werden muss.

Sie werden während des Konfigurierens von PHP (./configure), mit einem Fehler wie dem Folgenden konfrontiert:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Stellen Sie sicher, dass Sie Installation gründlich gelesen haben und beachten Sie, dass sowohl flex als auch bison zum Kompilieren von PHP installiert sein müssen. Abhängig von Ihrem System müssen Sie flex und bison entweder aus einer Quelle oder einem Paket wie z.B. RPM installieren.

Warum bekomme ich folgende Meldung, wenn ich versuche Apache zu starten?

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

Dieser Fehler tritt in der Regel auf, wenn man den Apache-Kern als gemeinsam verwendete DSO-Bibliothek kompiliert. Versuchen Sie Apache neu zu konfigurieren und stellen Sie sicher, dass zumindest die folgenden Flags gesetzt sind:

--enable-shared=max --enable-rule=SHARED_CORE

Für weitere Informationen lesen Sie die Apache-INSTALL-Datei oder die Apache-» DSO-Handbuchseite.

Wenn ich configure ausführe, bekomme ich die Fehlermeldung, dass die include-Dateien oder die GD-, gdbm- oder andere etc. Bibliotheken nicht gefunden werden konnten.

Es ist möglich, das configure-Skript so anzupassen, dass es nicht nur in Standard-Pfaden nach Headerdatei und Bibliotheken sucht, indem dem C-Präprozessor und -Linker zusätzliche Flags übergeben werden:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
Wenn Sie (aus welchem Grund auch immer) eine csh-Variante als Login-Shell verwenden, dann nutzen Sie folgende Flags:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

Wenn die Datei language-parser.tab.c kompiliert wird, erscheinen Fehler mit der Meldung yytname undeclared.

Sie müssen Bison updaten. Die aktuelle Version findet sich unter » http://www.gnu.org/software/bison/bison.html.

Wenn ich make ausführe, scheint alles normal zu verlaufen, aber sobald es versucht, die Applikation zu linken, beschwert es sich, einige Dateien nicht finden zu können.

Einige alte Versionen von make platzieren die kompilierten Versionen der Dateien nicht in das functions-Verzeichnis im gleichen Verzeichnis. Versuchen Sie, cp *.o functions auszuführen und danach erneut make zu starten, um zu prüfen, ob sich das Problem so lösen lässt. Sollte es dann funktionieren, empfehlen wir, Ihre Version von GNU make zu aktualisieren.

Wenn PHP gelinkt wird, beschwert es sich über undefinierte Referenzen.

Schauen Sie sich die Link-Zeile an und stellen Sie sicher, dass alle nötigen Bibliotheken am Ende mit eingeschlossen werden. Häufig werden '-ldl' und Datenbankbibliotheken vergessen.

Einige Leute haben berichtet, dass sie '-ldl' unmittelbar nach libphp4.a einfügen mussten, wenn sie PHP mit Apache gelinkt haben.

Ich habe die Schritte, die zur Installation des Apache-Moduls unter Unix nötig sind, befolgt, aber meine PHP-Skripte sind im Browser zu sehen oder ich werde aufgefordert, die Dateien zu speichern.

Das bedeutet, dass das PHP-Modul nicht aufgerufen wird. Sie sollten folgende drei Dinge überprüfen:

  • Stellen Sie sicher, dass das httpd-Binary, das Sie ausführen, tatsächlich das neue httpd-Binary ist, das sie kompiliert haben. Um das zu tun versuchen Sie, /path/to/binary/httpd -l auszuführen. Wenn mod_php4.c nicht auftaucht, führen Sie nicht das korrekte Binary aus. Finden und installieren Sie das korrekte Binary.
  • Stellen Sie sicher, dass Sie den korrekten Mime-Type in einer Ihrer Apache .conf-Datei angegeben haben. Er sollte AddType application/x-httpd-php .php lauten. Stellen Sie ebenfalls sicher, dass diese AddType-Anweisung sich nicht in einem <Virtualhost>- oder <Directory>-Block befindet, da dies verhindern würde, dass sie sich auf das Verzeichnis Ihres Testskript auswirkt.
  • Der Standardort der Apache-Konfigurationsdateien hat sich von Apache 1.2 zu Apache 1.3 verändert. Sie sollten sicherstellen, dass die Konfigurationsdatei, zu der sie die AddType-Anweisung hinzugefügt haben, diejenige ist, die auch verarbeitet wird. Sie können einen offensichtlichen Syntaxfehler oder eine andere eindeutige Änderung in Ihre httpd.conf einfbauen, um dies zu überprüfen.

Es heißt, es muss --activate-module=src/modules/php4/libphp4.a benutzt werden, aber diese Datei existiert nicht, also habe ich es zu --activate-module=src/modules/php4/libmodphp4.a geändert, aber es funktioniert nicht.

Die Datei libphp4.a soll gar nicht existieren, Apache wird sie selbst generieren.

Wenn ich versuche, Apache mit PHP als statisches Modul mittels --activate-module=src/modules/php4/libphp4.a zu kompilieren, kommt die Fehlermeldung, mein kompiler sei nicht ANSI-konform.

Das ist eine irreführende Fehlermeldung des Apache, die in aktuellen Versionen behoben ist.

Wenn ich versuche, PHP mittels der Option --with-apxs zu kompilieren, bekomme ich komische Fehlermeldungen.

Hier sind drei Dinge zu überprüfen: Wenn Apache das apxs-Perl-Skript generiert, werden manchmal aus unerfindlichen Gründen nicht die richtigen Kompiler- und Variablen-Flags verwendet. Suchen Sie Ihr apxs-Skript (probieren Sie das Kommando which apxs); oft liegt es unter /usr/local/apache/bin/apxs oder /usr/sbin/apxs. Öffnen Sie es und überprüfen Sie es auf Zeilen, die ähnlich wie folgende aussehen:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
Wenn Sie so etwas sehen, haben Sie Ihr Problem gefunden. Sie enthalten eventuell nur Leerzeichen oder anderen inkorrekte Werte, wie 'q()'. Ändern Sie die Zeilen wie folgt:
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
Das zweite mögliche Problem kann unter Red Hat 6.1 und 6.2 auftauchen. Das apxs-kcript, das Red Hat ausliefert, ist fehlerhaft. Suchen sie nach dieser Zeile:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Falls Sie die Zeile sehen, ändern Sie diese in
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Zu guter Letzt, wenn sie Apache neu installieren, fügen Sie ein make clean nach dem ./configure und vor dem make ein.

Während make bekomme ich Fehler in microtime und jede Menge RUSAGE_-Zeugs.

Wenn während des make-Teils der Installation Probleme auftauchen, die wie folgt aussehen:

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

ist Ihr System beschädigt. Sie müssen Ihre /usr/include-Dateien reparieren, indem Sie ein glibc-devel-Paket installieren, dessen Version mit der Ihrer glibc übereinstimmt. Das hat absolut nichts mit PHP zu tun. Um sich selbst davon zu überzeugen, führen Sie folgenden einfachen Test durch:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
Wenn hier Fehler auftauchen, wissen sie, dass Ihre include-Dateien fehlen oder fehlerhaft sind.

Beim Kompilieren von PHP mit MySQL läuft configure zwar ohne Probleme, aber beim Ausführen von make bekomme ich einen Fehler wie den Folgenden: 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' Was habe ich falsch gemacht?

Zuerst ist es wichtig, dass Sie sich darüber im Klaren sind, dass dies eine Warnung ist und kein Fehler. Weil dies aber oft die letzte sichtbare Ausgabe von make ist, sieht es oft wie ein Fehler aus. Natürlich bricht der Kompiler ab, falls Sie ihn so konfiguriert haben, dass er bei Warnungen abbrechen soll. Beachten Sie, dass die MySQL-Unterstützung standardmäßig aktiviert ist.

Hinweis:

Bei PHP 4.3.2 sehen Sie auch den folgenden Text nachdem das Kompilieren (make) beendet wurde:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

Ich möchte mein PHP aktualisieren. Wo kann ich die ./configure-Zeile finden, die von meiner aktuellen PHP-Version verwendet wird?

Entweder schauen Sie in die config.nice-Datei im Quellbaum Ihrer aktuellen PHP-Version nach, oder Sie führen folgendes Skript aus:

<?php phpinfo(); ?>
Zu Beginn der Ausgabe wird die ./configure-Zeile angezeigt.

Wenn ich PHP mit der GD-Bibliothek kompiliere, tauchen seltsame Kompilerfehler auf oder PHP startet nicht (Segfault).

Stellen Sie sicher, dass PHP und die GD-Bibliothek gegen die selben Bibliotheken wie libPNG gelinkt sind.

Wenn ich PHP kompiliere habe ich den Eindruck zufällige Fehler zu bekommen. Ich verwende Solaris.

Die Verwendung von nicht-GNU-Programmen beim Kompilieren kann Probleme verursachen. Verwenden sie GNU-Programme um sicherzustellen, dass das Kompilieren fehlerfrei klappt. Z.B. wird auf Solaris die Verwendung der SunOS-BSK-kompatiblen Version oder der Solaris-Version von sed nicht funktionieren. Verwenden Sie stattdessen die GNU- oder Sun-POSIX-(xpg4-)Version von sed. Links: » GNU sed, » GNU flex, und » GNU bison.

User Contributed Notes

There are no user contributed notes for this page.


PHP verwenden

Diese Rubrik behandelt viele Fehler, die möglicherweise beim Schreiben von PHP-Skripten auftreten.

  1. Ich kann mir die Reihenfolge der Parameter von PHP-Funktionen nicht merken - gibt es ein Schema?
  2. Ich möchte ein PHP-Skript schreiben, das Daten von beliebigen Formularen verarbeiten kann. Woher weiß ich, welche Variablen über die POST-Methode verfügbar sind?
  3. Ich möchte alle einfachen Anführungszeichen (') in einen Backslash gefolgt von einem einfachen Anführungszeichen (\') ersetzen lassen. Wie kann ich das mit einem regulären Ausdruck machen? Ich möchte außerdem " zu \" und \ zu \\ konvertieren.
  4. Wenn ich den folgenden Code ausführe, wird die Ausgabe in der falschen Reihenfolge ausgegeben: <?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> Woran liegt das?
  5. Wo sind meine Zeilenumbrüche geblieben? <pre> <?php echo "Das soll die erste Zeile sein."; ?> <?php echo "Das soll nach dem obigen Zeilenumbruch erscheinen."; ?> </pre>
  6. Ich bekomme die Meldung 'Warning: Cannot send session cookie - headers already sent...' oder 'Cannot add header information - headers already sent...'.
  7. Wie kann ich auf Informationen aus dem Request-Header zugreifen?
  8. Wenn ich versuche, Authentifizierung mit IIS zu nutzen, bekomme ich die Meldung 'No Input file specified'.
  9. Windows: Ich kann keine auf einem anderen Rechner freigegebenen Dateien aufrufen, wenn ich den IIS verwende.
  10. Wie kann ich XML und PHP mischen? PHP beschwert sich über meine <?xml-Tags!
  11. Wo kann ich eine komplette Liste der mir zur Verfügung stehenden Variablen finden?
  12. Wie kann ich PDF-Dateien generieren, ohne die nicht-freie und kommerzielle Bibliothek PDFLib zu verwenden? Ich suche etwas, das frei ist und keine externen PDF-Bibliotheken benötigt.
  13. Einige PHP-Direktiven akzeptieren nicht nur Integer-Byte-Werte, sondern auch abgekürzte Byte-Werte. Welche Abkürzungen gibt es?
Ich kann mir die Reihenfolge der Parameter von PHP-Funktionen nicht merken - gibt es ein Schema?

PHP besteht aus Hunderten externer Bibliotheken, so dass dies manchmal etwas durcheinander erscheint. Eine einfache Regel ist aber wie folgt:

Parameter von Array-Funktionen sind als "needle, haystack" (Nadel, Heuhaufen) geordnet, während die Parameter von String-Funktionen genau andersrum geordnet sind, also als "haystack, needle" (Heuhaufen, Nadel).

Ich möchte ein PHP-Skript schreiben, das Daten von beliebigen Formularen verarbeiten kann. Woher weiß ich, welche Variablen über die POST-Methode verfügbar sind?

PHP bietet viele vordefinierte Variablen, wie das superglobale $_POST. Sie können $_POST mit einer Schleife durchlaufen, da es sich um ein assoziatives Array mit allen über die POST-Methode übertragenen Variablen handelt. Als Beispiel verwenden wir die foreach-Schleife, um (mit der Funktion empty()) auf leere Werte zu prüfen, und geben diese Werte aus.

<?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 "Keiner der POST-Werte ist leer. Die Werte sind:\n";
var_dump($post);
} else {
print "Wir haben " . count($empty) . " leere Werte:\n";
print "Alle Werte:\n"; var_dump($post);
print "Leer:\n"; var_dump($empty);
exit;
}
?>

Ich möchte alle einfachen Anführungszeichen (') in einen Backslash gefolgt von einem einfachen Anführungszeichen (\') ersetzen lassen. Wie kann ich das mit einem regulären Ausdruck machen? Ich möchte außerdem " zu \" und \ zu \\ konvertieren.

Falls Sie dies für eine Datenbank tun möchten, sollten Sie den Maskierungsmechanismus nutzen, der für diese Datenbank vorgesehen ist. Z. B. sollten Sie mysql_real_escape_string() unter MySQL und pg_escape_string() unter PostgreSQL nutzen. Es gibt außerdem die generische Funktionen addslashes() und stripslashes(), die häufig in älterem PHP-Code genutzt werden.

Wenn ich den folgenden Code ausführe, wird die Ausgabe in der falschen Reihenfolge ausgegeben:
<?php
function myfunc($argument)
{
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
Woran liegt das?

Um das Ergebnis Ihrer Funktion in einem Ausdruck verwenden zu können (um es z. B. wie im obigen Beispiel mit dem anderen String zu verbinden), müssen Sie den Wert mit return zurückgeben und ihn nicht mit echo ausgeben.

Wo sind meine Zeilenumbrüche geblieben?
<pre>
<?php echo "Das soll die erste Zeile sein."; ?>
<?php echo "Das soll nach dem obigen Zeilenumbruch erscheinen."; ?>
</pre>

In PHP können Code-Blöcke entweder mit "?>" oder mit "?>\n" enden (\n steht für Zeilenumbruch). Im obigen Beispiel sind die ausgegebenen Zeilen daher in einer Zeile, denn PHP lässt die Zeilenumbrüche nach den Block-Ende-Zeichen weg. Wenn Sie möchten, dass PHP einen Zeilenumbruch ausgibt, müssen Sie nach jedem Code-Block einen zusätzlichen Zeilenumbruch einfügen.

Warum macht PHP das so? Wenn Sie normales HTML formatieren, erleichert PHP Ihnen die Arbeit, da Sie meist diesen Zeilenumbruch gar nicht haben möchten. Würde PHP diesen Zeilenumbruch ausgeben, müssten Sie sehr lange Zeilen schreiben und Ihren Code damit unlesbar machen.

Ich bekomme die Meldung 'Warning: Cannot send session cookie - headers already sent...' oder 'Cannot add header information - headers already sent...'.

Die Funktionen header(), setcookie() und die Session-Funktionen müssen dem Output-Stream Header hinzufügen. Header können aber nur gesendet werden, wenn Sie vor allen anderen Daten gesendet werden. Vor dem Aufruf dieser Funktionen darf also keine Ausgabe (wie z. B. HTML-Code) stattfinden. Die Funktion headers_sent() prüft, ob Ihr Skript bereits Header gesendet hat. Nützlich sind in diesem Zusammenhang auch die Funktionen zur Ausgabesteuerung.

Wie kann ich auf Informationen aus dem Request-Header zugreifen?

Wenn Sie PHP als Apache-Modul laufen lassen, liefert Ihnen die Funktion getallheaders() die gewünschten Informationen. Der folgende Code gibt alle Request-Header aus:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
echo "headers[$name] = $content<br />\n";
}
?>

Siehe auch apache_lookup_uri(),
apache_response_headers() und
fsockopen().

Wenn ich versuche, Authentifizierung mit IIS zu nutzen, bekomme ich die Meldung 'No Input file specified'.

Das Sicherheitsmodell des IIS ist hier fehlerhaft. Dies ist ein Problem, das bei allen CGI-Programmen auftritt, die unter dem IIS laufen. Als Workaround können Sie eine leere HTML-Datei, die nicht von PHP geparst wird, als Eingangsseite in ein per Authentifizierung geschütztes Verzeichnis legen. Anschließend leiten Sie den Browser durch ein META-Tag auf die PHP-Seite weiter oder sie setzen einen Link auf die PHP-Seite. PHP erkennt dann die Authentifizierung korrekt. Auch auf anderen NT-Web-Servern sollte dieses Problem nicht auftauchen. Weitere Informationen finden Sie auch hier: » http://support.microsoft.com/kb/q160422/. Lesen Sie auch den Manual-Abschnitt zur HTTP-Authentifizierung mit PHP.

Windows: Ich kann keine auf einem anderen Rechner freigegebenen Dateien aufrufen, wenn ich den IIS verwende.

Sie müssen die Go to Internet Information Services ändern. Suchen Sie Ihre PHP-Datei und rufen Sie deren Eigenschaften auf. Wechseln Sie auf das Register File Security, klicken Sie dort auf Edit -< Anonymous access and authentication control.

Sie können das Problem beheben, indem Sie entweder den Haken bei Anonymous Access entfernen und ihn bei Integrated Window Authentication belassen, oder indem Sie Anonymous Access ankreuzen und dann die Berechtigungen der Benutzer, die keinen Zugriff bekommen sollen, anpassen.

Wie kann ich XML und PHP mischen? PHP beschwert sich über meine <?xml-Tags!

Um <?xml in Ihren PHP-Code einzufügen müssen Sie die Kurzform der öffnenden PHP-Tags abschalten, indem Sie in Ihrer php.ini short_tags auf 0 setzen. Sie können diese Direktive nicht mit der Funktion ini_set() setzen. Sie können unabhängig davon, ob short_open_tags aktiviert oder deaktiviert ist, z. B. <?php echo '<?xml'; ?> verwenden. Der Standardwert für diese Direktive ist On.

Wo kann ich eine komplette Liste der mir zur Verfügung stehenden Variablen finden?

Lesen Sie die Manual-Seite zu vordefinierten Variablen, die eine (unvollständige) Liste der vordefinierten Variablen enthält, die Ihren Skripten zur Verfügung stehen. Eine komplette Liste der verfügbaren Variablen (und viele weitere Informationen) können Sie sehen, wenn Sie die Funktion phpinfo() aufrufen. Beachten Sie auch den Abschnitt zu Variablen außerhalb von PHP, der verschiedene Szenarien für externen Variablen wie HTML-Formulare, Cookies oder den URL beschreibt.

Wie kann ich PDF-Dateien generieren, ohne die nicht-freie und kommerzielle Bibliothek PDFLib zu verwenden? Ich suche etwas, das frei ist und keine externen PDF-Bibliotheken benötigt.

Es gibt einige in PHP geschriebene Alternativen wie » FPDF und » TCPDF.

Einige PHP-Direktiven akzeptieren nicht nur Integer-Byte-Werte, sondern auch abgekürzte Byte-Werte. Welche Abkürzungen gibt es?

Die verfügbaren Abkürzungen sind K (für Kilobytes), M (für Megabytes) und G (für Gigabytes), Groß-/Kleinschreibung spielt dabei keine Rolle. Alle anderen Werte werden als Byte-Werte erkannt. 1M entspricht z. B. einem Megabyte oder 1048576 Bytes. 1K entspricht einem Kilobyte oder 1024 Bytes. Diese abgekürzte Schreibweise kann in der php.ini und in der Funktion ini_get() verwendet werden. Es ist zu beachten, dass der numerische Wert nach int umgewandelt wird; beispielsweise wird 0.5M als 0 interpretiert.

Hinweis: Kilobyte versus Kibibyte

Die PHP-Notation beschreibt ein Kilobyte als Entsprechung von 1024 Bytes, während der IEC-Standard dies als Kibibyte bezeichnet. Zusammenfassung: k und 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.


Sicheres Password Hashing

Dieser Absatz erklärt, warum Hash Funktionen zur sicheren Passwortspeicherung benutzt werden, und wie dies am effektivsten bewerkstelligt werden kann.

  1. Warum sollte ich die Passwörter der User meiner Anwendung hashen?
  2. Warum sind verbreitete Hashfunktionen wie md5 und sha1 nicht für die Speicherung von Passwörtern geeignet?
  3. Wie sollte ich meine Passwörter hashen, wenn die üblichen Hashfunktionen unbrauchbar sind?
  4. Was ist ein Salt?
  5. Wie speichere ich meine Salts?
Warum sollte ich die Passwörter der User meiner Anwendung hashen?

Passworthashing ist eine der grundlegendsten Sicherheitsüberlegungen, die beim Design einer Anwendung bedacht werden müssen. Ohne Hashing können im Falle eines erfolgreichen Angriffs alle Userpasswörter in Ihrer Datenbank von einem Angreifer gestohlen und ohne Umwege in anderen Anwendungen (seien es Ihre oder die Anderer) benutzt werden. Dies ist oft der Fall, da viele User für verschiedene Dienste die gleichen Passwörter verwenden.

Wenn Sie Passwörter vor dem Abspeichern in der Datenbank hashen, machen Sie es einen Angreifer schwerer die ursprünglichen Passwörter herauszufinden. Sie haben jedoch weiterhin die Möglichkeit eingegebene Userpasswörter zu hashen und die Hashwerte zu vergleichen um herauszufinden, ob der User das richtige Passwort eingegeben hat.

Es ist jedoch wichtig zu wissen, dass Hashen nur das Auslesen der Passwörter aus dem Datenspeicher (z.B.: Datenbank oder Datei) erschwert. Sollte es einen Angreifer gelingen Code in Ihre Anwendung einzuschleusen, so kann er die Passwörter der User evtl. Auslesen bevor dieses gehasht werden.

Warum sind verbreitete Hashfunktionen wie md5() und sha1() nicht für die Speicherung von Passwörtern geeignet?

Hashalgorithmen wie MD5, SHA1 und SHA256 sind auf Geschwindigkeit und Effizienz optimiert. Mit modernen Techniken und leistungsstarker Hardware ist es aber trivial geworden diese Hashalgorithmen mit "brute force" Attacken anzugreifen.

Weil moderne Computer diese Hashalgorithmen leicht brechen können, werden diese von Sicherheitsspezialisten nicht für die Speicherung von Passwörtern empfohlen.

Wie sollte ich meine Passwörter hashen, wenn die üblichen Hashfunktionen unbrauchbar sind?

Wenn es um das Hashen von Passwörtern geht müssen zwei wichtige Sachen bedacht werden: Der Berechnungsaufwand und das Salt. Wenn es länger dauert einen Hash zu berechnen wird ein Brute Force Angriff stark verzögert. Jedoch ist zu beachten, dass der Berechnungsaufwand sich im normalen Betrieb nicht negativ auf die Performance der Anwendung auswirkt. Das Salt hingegen dient dazu, die Erstellung von vorberechneten Rainbowtables zu verhindern, da durch das Salt auch gleiche Passwörter unterschiedliche Hashes erhalten.

PHP bietet eine native Passworthashing API die sich auf eine sichere Art um das Hashen und Verifizieren von Passwörtern kümmert.

Eine andere Option ist die crypt() Funktion, die mehrere Hashalgorithmen unterstützt. Wenn diese Funktion benutzt wird, ist es garantiert, dass der Hashalgorithmus unterstützt wird, da PHP native Implementierungen für die Algorithmen besitzt, die benutzt werden, wenn von dem Betriebsystem nicht angebotene Algorithmen benutzt werden.

Der empfohlene Algorithmus für das Hashen von Passwörtern ist Blowfish, welcher auf als Standardalgorithmus von der Passwort Hashing API benutzt wird, da dieser einen signifikant höheren Berechnungsaufwand als MD5 oder SHA1 voraussetzt und trotzdem weiterhin skalierbar ist.

Bitte beachten Sie: Wenn Sie crypt() benutzen um Passwörter zu verifizieren müssen sie dafür sorgen, Timing Attacken zu verhindern. Dies kann durch Stringvergleiche mit konstanter Laufzeit geschehen. Jedoch bieten die PHP Vergleichsoperatoren == und === keine konstante Laufzeit. Da jedoch password_verify() eine konstante Laufzeit besitzt ist es stark empfohlen die native Passwort Hashing API zu benutzen, wenn dies möglich ist.

Was ist ein Salt?

Ein kryptografisches Salt sind Daten, die während des Hashens an das Passwort angefügt werden um die Möglichkeit des Angriffs über Rainbowtables zu erschweren. Rainbowtables sind bereits vorberechnete Paare (Schlüssel, Hash), die benutzt werden können, um für einen gegebenen Hash das vorberechnete Passwort nachzuschlagen.

In einfachen Worten: Ein Hash sind zusätzliche Daten, die es erschweren das Passwort zu knacken. Es gibt Onlinedienste bei denen man für einen gegebenen Hash das dazugehörige Passwort herrausfinden kann. Die Benutzung eines Salts macht es unpraktisch bis unmöglich das Passwort durch die Benutzung dieser Dienste zu finden.

Die Funktion password_hash() generiert ein zufälliges Salt, sollte beim Aufruf der Funktion keines übergeben werden. Dies ist generell der einfachste und sicherste Ansatz.

Wie speichere ich meine Salts?

Die Funktionen password_hash() oder crypt() geben den Salt als einen Teil des generierten Hashs zurück. Dieser Wert sollte unverändert abgespeichert werden, da er Informationen über den Hashalgorithmus enthält und direkt an die Funktion password_verify() oder crypt() übergeben werden kann um ein Passwort zu verifzieren.

Das folgende Diagramm zeigt das Format eines Rückgabewertes der Funktionen crypt() oder password_hash(). Wie sie sehen können, enthalten die Hashes alle Informationen über Hashalgorithmus und Salt, wie sie für die spätere Verifikation von Passwörtern benötigt werden.

Die Komponenten des Rückgabewerten von password_hash und crypt in dieser Reihenfolge: Der benutze Algorithmus, die Optionen des Algorithmus, das benutzte Salt und das gehashte Passwort.

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.


PHP und HTML

PHP und HTML interagieren stark: PHP kann HTML generieren und HTML kann Informationen an PHP weitergeben. Bevor Sie diese FAQ lesen, sollten Sie verstanden haben, wie Sie auf Variablen aus externen Quellen zugreifen können. Die Manual-Seite zu diesem Thema enthält viele Beispiele, die das Verständnis erleichtern.

  1. Wie muss ich kodieren/dekodieren, wenn ich einen Wert über ein Formular/einen URL weitergeben möchte?
  2. Ich versuche ein <input type="image">-Tag zu benutzen, aber die Variablen $foo.x and $foo.y sind nicht verfügbar. Auch $_GET['foo.x'] existiert nicht. Wo finde ich diese?
  3. Wie kann ich Array aus einem HTML-Formular erstellen?
  4. Wie bekomme ich alle Werte aus einem "select multiple"-HTML-Tag?
  5. Wie kann ich eine Variable von JavaScript an PHP übergeben?
Wie muss ich kodieren/dekodieren, wenn ich einen Wert über ein Formular/einen URL weitergeben möchte?

Es gibt mehrere Stufen, für die Encoding wichtig ist. Angenommen, Sie haben einen String $data, der den String, den Sie in nicht-kodierter Weise weitergeben möchten, enthält. Dann sind dies die relevanten Stufen:

  • HTML-Interpretation: Wenn Sie einen zufälligen String angeben wollen, müssen Sie ihn in die doppelte Anführungszeichen einschließen und htmlspecialchars() auf den gesamten Wert anwenden.

  • URL: Ein URL besteht aus mehreren Teilen. Wenn Sie wollen, dass Ihre Daten als ein Element interpretiert werden, dann müssen Sie Ihre Daten mit urlencode() kodieren.

Beispiel #1 Ein verstecktes HTML-Formularelement

<?php
echo '<input type="hidden" value="' . htmlspecialchars($data) . '" />'."\n";
?>

Hinweis: Es wäre falsch, urlencode() auf $data anzuwenden, da es die Aufgabe des Browsers ist, die Daten zu kodieren. Alle populären Browser machen dies auch korrekt. Beachten Sie, dass dies unabhängig von der verwendeten Methode (also z. B. GET oder POST) geschieht. Feststellen werden Sie dies aber nur bei GET-Anfragen, da POST-Anfragen meist versteckt geschehen.

Beispiel #2 Daten, die vom Benutzer bearbeitet werden sollen

<?php
echo "<textarea name='mydata'>\n";
echo htmlspecialchars($data)."\n";
echo "</textarea>";
?>

Hinweis: Die Daten werden wie Browser wie gewünscht ausgegeben, da der Browser die HTML-escapten Symbole interpretiert. Nach dem Abschicken, egal ob via GET oder POST, werden die Daten für den Transfer kodiert (mit urlencode()) und von PHP direkt wieder dekodiert (mit urldecode()). Sie müssen also für die Kodierung und Dekodierung nicht selbst sorgen, die Browser und PHP erledigen dies automatisch für Sie.

Beispiel #3 In einem URL

<?php
echo '<a href="' . htmlspecialchars("/nextpage.php?stage=23&data=" .
urlencode($data)) . '">'."\n";
?>

Hinweis: Hier wird eine HTML-GET-Anfrage gefakt, deswegen müssen Sie die Daten manuell mit urlencode() kodieren.

Hinweis: Sie müssen htmlspecialchars() auf den gesamten URL anwenden, da der URL als Wert eines HTML-Attributs auftritt. In diesem Fall wird der Browser zuerst etwas wie "un-htmlspecialchars()" auf den Wert anwenden und dann erst den URL weitergeben. PHP wird den URL korrekt verstehen, da Sie die Daten mit urlencode() kodiert haben. Sie werden feststellen, dass das & im URL durch &amp; ersetzt wird. Auch wenn die meisten Browser richtig arbeiten, falls Sie diese Ersetzung vergessen sollten, sollten Sie sich trotzdem nicht darauf verlassen. Das bedeutet, dass Sie - auch wenn Ihr URL nicht dynamisch ist - trotzdem htmlspecialchars() auf den URL anwenden müssen.

Ich versuche ein <input type="image">-Tag zu benutzen, aber die Variablen $foo.x and $foo.y sind nicht verfügbar. Auch $_GET['foo.x'] existiert nicht. Wo finde ich diese?

Wenn ein Formular abgeschickt werden soll, ist es möglich, ein Bild statt des Standard-Submit-Buttons zu verwenden, indem Sie ein Tag wie das folgende verwenden:

<input type="image" src="image.gif" name="foo" />
Wenn der Benutzer irgendwo auf das Bild klickt, wird das zugehörige Formular zusammen mit zwei zusätzlichen Variablen übertragen: foo.x und foo.y.

Da foo.x und foo.y in PHP ungültige Variablennamen erzeugen würden, werden Sie automatisch in $foo_x und $foo_y konvertiert. Die Punkte werden also durch Unterstriche ersetzt. Sie können auf diese Variablen also genauso wie im Abschnitt Variablen aus externen Quellen zugreifen, z. B. $_GET['foo_x'].

Hinweis:

Leerzeichen in Namen von Formularelementen werden in Unterstriche konvertiert.

Wie kann ich Array aus einem HTML-Formular erstellen?

Um die Formularwerte als Array im PHP-Skript zur Verfügung zu haben, müssen Sie die <input>, <select> or <textarea>-Felder wie folgt benennen:

<input name="MeinArray[]" />
<input name="MeinArray[]" />
<input name="MeinArray[]" />
<input name="MeinArray[]" />
Beachten Sie die eckigen Klammern hinter dem Variablen-Namen, denn dadurch wird das Array erst erzeugt. Sie können Felder in verschiedenen Arrays gruppieren, wenn Sie verschiedenen Feldern die gleichen Namen geben:
<input name="MeinArray[]" />
<input name="MeinArray[]" />
<input name="MeinAnderesArray[]" />
<input name="MeinAnderesArray[]" />
Daraus werden zwei Arrays, MeinArray und MeinAnderesArray erstellt. Es ist auch möglich, spezielle Schlüssel anzugeben:
<input name="AnderesArray[]" />
<input name="AnderesArray[]" />
<input name="AnderesArray[email]" />
<input name="AnderesArray[telefon]" />
Das Array AnderesArray enthält daraufhin die Schlüssel 0, 1, email und telefon.

Hinweis:

Die Angabe von Array-Schlüsseln ist in HTML optional. Wenn Sie keinen Schlüssel angeben, wird das Array in der Formular-Reihenfolge gefüllt. Im ersten Beispiel enthält also die Schlüssel 0, 1, 2 und 3.

Siehe auch: Array-Funktionen und Variablen aus externen Quellen.

Wie bekomme ich alle Werte aus einem "select multiple"-HTML-Tag?

Mit einem "select multiple"-Tag können Benutzer mehrere Werte aus einer Liste auswählen. Diese Werte werden dann an den "action handler" des Formulars (z. B. ein PHP-Skript) übergeben. Problematisch ist dabei, dass alle mit demselben Namen übergeben werden, z. B.:

<select name="var" multiple="yes">
Jede ausgewählte Option wird übergeben als:
var=option1
var=option2
var=option3
Jede Option wird den Inhalt der vorherigen $var-Variablen überschreiben. Die Lösung ist, die spezielle PHP-Lösung hierfür zu verwenden. Sie sollten das Tag wie folgt umschreiben:
<select name="var[]" multiple>
PHP weiß dann, dass $var als Array behandelt werden soll. Jede ausgewählte Wert wird dem Array hinzugefügt. Das erste Element wird zu $var[0], das nächste zu $var[1] etc. Die count()-Funktion kann benutzt werden, um herauszufinden, wie viele Optionen ausgewählt wurden. Mit der sort()-Funktion können Sie bei Bedarf das Array sortieren.

Beachten Sie, dass, falls Sie JavaScript benutzen, die eckigen Klammern [] im Feldnamen Probleme machen können, wenn Sie versuchen, über den Namen auf das Feld zu verweisen. Benutzen Sie stattdessen die numerische ID des Formularfelds oder schließen Sie den Variablennamen in einfache Anführungszeichen ein und benutzen Sie dies als den Index, z. B.:

variable = document.forms[0].elements['var[]'];

Wie kann ich eine Variable von JavaScript an PHP übergeben?

Da JavaScript (normalerweise) nur auf dem Client läuft, während PHP (normalerweise) auf Servern läuft, und da HTTP ein "status-loses" Protokoll ist, können zwischen den beiden Sprachen keine Variablen direkt ausgetauscht werden.

Allerdings ist es trotzdem möglich, Variablen zwischen den beiden zu übergeben. Eine Möglichkeit ist, den JavaScript-Code mit PHP zu generieren. Außerdem muss die angezeigte Seite sich regelmäßig selbst aktualisieren und dabei bestimmte Variablen an das PHP-Skript übergeben. Das folgende Beispiel zeigt wie Sie dies tun können -- es ermöglicht PHP, die Bildschirmauflösung (Höhe und Breite) zu ermitteln, was normalerweise nur Client-seitig möglich ist.

Beispiel #4 JavaScript mit PHP generieren

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
// Ausgabe der beiden Größenangaben
echo "Die Bildschirmbreite ist: ". $_GET['width'] ."<br />\n";
echo "Die Bildschirmhöhe ist: ". $_GET['height'] ."<br />\n";
} else {
// Übergabe der Größenangaben
// (der ursprüngliche 'QUERY_STRING' wird beibehalten;
// POST-Variablen müssen anders behandelt werden)

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

PHP kann auf Win32 Plattformen benutzt werden, um auf COM und DCOM Objekte zuzugreifen.

  1. Ich habe eine DLL-Datei erstellt, um etwas zu berechnen. Kann ich diese DLL-Datei auch in PHP benutzen?
  2. Was bedeutet 'Unsupported variant type: xxxx (0xxxxx)'?
  3. Ist es möglich, visuelle Objekte in PHP zu verändern?
  4. Kann ich ein COM-Objekt in einer Session speichern?
  5. Wie kann ich COM-Fehler abfangen?
  6. Kann ich DLL-Dateien aus PHP-Skripten wie in Perl generieren?
  7. Was bedeutet 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?
  8. Wie kann ich ein COM-Object von einem entfernten Server ausführen?
  9. Ich bekomme die Meldung 'DCOM is disabled in C:\path...\scriptname.php on line 6' angezeigt, was kann ich tun?
  10. Ist es möglich ein ActiveX-Objekt auf einer Seite mit PHP zu laden/manipulieren?
  11. Ist es möglich, eine laufende Instanz einer Komponente zu erhalten?
  12. Gibt es einen Weg, um ein Ereignis von einem COM-Objekt zu verarbeiten?
  13. Ich habe Probleme, wenn ich versuche eine Methode eines COM-Objekts auszuführen, die mehr als ein Interface implementiert. Was kann ich tun?
  14. PHP funktioniert mit COM, aber was ist mit COM+?
  15. Wenn PHP COM-Objekte manipulieren kann, könnten wir in Zukunft MTS in Verbindung mit PHP benutzen, um Komponenten-Ressourcen zu verwalten?
Ich habe eine DLL-Datei erstellt, um etwas zu berechnen. Kann ich diese DLL-Datei auch in PHP benutzen?

Wenn es eine einfache DLL-Datei ist, gibt es noch keinen Weg diese auch in PHP zu benutzen. Wenn die DLL-Datei aber einen COM-Server enthält, können Sie diese möglicherweise benutzen, wenn sie das IDispatch Interface implementiert.

Was bedeutet 'Unsupported variant type: xxxx (0xxxxx)'?

Es gibt dutzende VARIANT-Typen und -Kombination. Die meisten werden bereits unterstützt, aber es gibt immer noch einige, die noch implementiert werden müssen. Arrays werden zum Beispiel noch nicht vollständig unterstützt. Nur eindimensional indexierte Arrays können zwischen PHP und COM ausgetauscht werden. Wenn Sie andere Typen finden, die nicht unterstützt werden, melden Sie diese bitte als Bug (wenn sie nicht schon gemeldet wurden) und stellen so viele Informationen zur Verfügung wie möglich.

Ist es möglich, visuelle Objekte in PHP zu verändern?

Generell ja, aber da PHP normalerweise als Web-Skriptsprache verwendet wird, läuft es im Webserver Kontext, also werden visuelle Objekte niemals auf dem Desktop des Servers erscheinen. Wenn Sie PHP für Anwendungsskripting benutzen, zum Beispiel in Verbindung mit PHP-GTK, gibt es keine Limitation bei Zugriff und Veränderung von visuellen Objekten durch COM.

Kann ich ein COM-Objekt in einer Session speichern?

Nein, können Sie nicht. COM-Instanzen werden als Resourcen behandelt und können somit nur im Kontext eines einzelnen Skripts benutzt werden.

Wie kann ich COM-Fehler abfangen?

Die COM-Erweiterung wirft eine com_exception, die Sie abfangen und dann das code-Member inspizieren können, um zu bestimmen, wie fortzufahren ist.

Kann ich DLL-Dateien aus PHP-Skripten wie in Perl generieren?

Nein, leider gibt es kein Tool, das für PHP verfügbar ist.

Was bedeutet 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?

Dieser Fehler kann mehrere Gründe haben:

  • Die CLSID ist falsch
  • Die angeforderte DLL-Datei fehlt
  • Die angeforderte Kompinente implementiert das IDispatch Interface nicht.

Wie kann ich ein COM-Object von einem entfernten Server ausführen?

Genauso, wie Sie lokale COM-Objekte ausführen. Sie müssen nur die IP der entfernten Maschine als zweiten Parameter zum COM-Konstruktor weitergeben.

Stellen Sie sicher, dass Sie com.allow_dcom =true in der php.ini gesetzt haben.

Ich bekomme die Meldung 'DCOM is disabled in C:\path...\scriptname.php on line 6' angezeigt, was kann ich tun?

Bearbeiten Sie die php.ini und setzen sie com.allow_dcom =true.

Ist es möglich ein ActiveX-Objekt auf einer Seite mit PHP zu laden/manipulieren?

Das hat nichts mit PHP zu tun. ActiveX-Objekte werden auf beim Benutzer geladen, wenn sie vom HTML-Dokument angefordert werden. Es gibt keine Verbindung zum PHP-Skript, also ist auch keine direkte Interaktion auf der Seite des Servers möglich.

Ist es möglich, eine laufende Instanz einer Komponente zu erhalten?

Mithilfe von Monikern ist das möglich. Wenn Sie mehrere Referenzen zum selben Word-Exemplar erhalten möchten, können sie dieses Exemplar erstellen, wie hier beschrieben:

<?php
$word = new COM("C:\docs\word.doc");
?>

Dieser Code erstellt ein neues Exemplar, wenn kein laufendes Exemplar verfügbar ist, oder er gibt ein Handle zum laufenden Exemplar, wenn diese verfügbar ist, zurück.

Gibt es einen Weg, um ein Ereignis von einem COM-Objekt zu verarbeiten?

Sie können einen Listener definieren und ihn mithilfe von com_event_sink() binden. Sie können com_print_typeinfo() benutzen, um eine Listener-Skelettklasse von PHP erstellen zu lassen.

Ich habe Probleme, wenn ich versuche eine Methode eines COM-Objekts auszuführen, die mehr als ein Interface implementiert. Was kann ich tun?

Die Antwort ist genauso einfach und unbefriedigend zugleich. Ich weiß es nicht genau, aber ich denke, Sie können nichts tun. Wenn jemand spezifischere Informationen darüber hat, lassen Sie es » mich wissen :)

PHP funktioniert mit COM, aber was ist mit COM+?

COM+ erweitert COM um ein Framework, um Komponenten über MTS und MSMQ zu verwalten, aber es gibt nichts Besonderes, das PHP unterstützen müsste, um solche Komponenten zu benutzen.

Wenn PHP COM-Objekte manipulieren kann, könnten wir in Zukunft MTS in Verbindung mit PHP benutzen, um Komponenten-Ressourcen zu verwalten?

PHP selbst verarbeitet Transaktionen noch nicht. Wenn also ein Fehler auftritt, wird kein Rollback gestartet. Wenn Sie Komponenten benutzen, die Transaktionen unterstützen, müssen Sie das Transaktions-Management selbst implementieren.

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.


Verschiedene Fragen

Es gibt diverse Fragen, die in keine andere Kategorie passen. Diese Fragen finden Sie hier.

  1. Wie entpacke ich Manuals unter Windows, die mit bz2 komprimiert wurden?
Wie entpacke ich Manuals unter Windows, die mit bz2 komprimiert wurden?

Wenn Sie keinen Entpacker haben, der bz2 entpacken kann, » laden Sie sich das Kommandozeilenprogramm von Redhat herunter (siehe Informationen weiter unten).

Wenn Sie nicht das Kommandozeilenprogramm verwenden wollen, dann können Sie kostenlose Tools wie den » Stuffit Expander, » UltimateZip, » 7-Zip, oder » Quick Zip verwenden. Wenn Sie » WinRAR oder » Power Archiver haben, können Sie die bz2-Dateien damit entpacken. Sollten Sie Total Commander (ehemals Windows Commander) verwenden, so gibt es dafür ein kostenloses bz2-Plugin auf der » Total Commander-Seite.

Das bzip2-Kommandozeilenprogramm von Redhat:

Benutzer von Win2k SP2 verwenden die aktuelle Version 1.0.2, alle anderen Windows-Benutzer sollten Version 1.00 nehmen. Nach dem Download sollten Sie die Datei in bzip2.exe umbenennen. Kopieren Sie diese zur leichteren Handhabung in ein Verzeichnis im Windows-Pfad, z.B. C:\Windows, wobei C: das Laufwerk Ihrer Windows-Installation ist.

Anmerkung: lang steht für die Sprache und x für das Format, z.B. pdf. Zum entpacken von php_manual_lang.x.bz2 folgen Sie diesen einfachen Schritten:

  • Öffenen Sie die Eingabeaufforderung
  • Springen Sie mit cd in das Verzeichnis, in dem Sie die heruntergeladene Datei php_manual_lang.x.bz2 gespeichert haben
  • Mit bzip2 -d php_manual_lang.x.bz2, entpacken Sie die Datei php_manual_lang.x im selben Verzeichnis

Wenn Sie die Datei php_manual_lang.tar.bz2 heruntergeladen haben, die viele HTML-Dateien enthält, gehen Sie genauso vor. Der einzige Unterschied ist, dass Sie eine Datei namens php_manual_lang.tar erhalten. Die meisten Entpacker unter Windows verstehen das tar Format wie z.B. » WinZip.

User Contributed Notes

There are no user contributed notes for this page.


Anhang

  • Die Geschichte von PHP und verwandten Projekten
    • Die Geschichte von PHP
    • Geschichte von PHP verwandten Projekten
    • Bücher über PHP
    • Publikationen über PHP
  • Migration von PHP 8.2.x auf PHP 8.3.x
    • Neue Features
    • Neue Klassen und Schnittstellen
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Sonstige Änderungen
    • Windows-Unterstützung
  • Migration von PHP 8.1.x auf PHP 8.2.x
    • Neue Features
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Sonstige Änderungen
    • Windows-Unterstützung
  • Migration von PHP 8.0.x auf PHP 8.1.x
    • Neue Features
    • Neue Klassen und Interfaces
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Sonstige Änderungen
  • Migration von PHP 7.4.x auf PHP 8.0.x
    • Neue Features
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Sonstige Änderungen
  • Migration von PHP 7.3.x auf PHP 7.4.x
    • Neue Features
    • Neue Klassen und Interfaces
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Entfernte Erweiterungen
    • Sonstige Änderungen
    • Windows-Unterstützung
  • Migration von PHP 7.2.x auf PHP 7.3.x
    • Neue Features
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features
    • Sonstige Änderungen
    • Windows-Unterstützung
  • Migration von PHP 7.1.x auf PHP 7.2.x
    • Neue Features
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features in PHP 7.2.x
    • Sonstige Änderungen
  • Migration von PHP 7.0.x nach PHP 7.1.x
    • Neue Features
    • Neue Funktionen
    • Neue globale Konstanten
    • Nicht abwärtskompatible Änderungen
    • Veraltete Features in PHP 7.1.x
    • Geänderte Funktionen
    • Sonstige Änderungen
    • Windows-Unterstützung
  • Migration von PHP 5.6.x nach PHP 7.0.x
    • Nicht abwärtskompatible Änderungen
    • Neue Features
    • Veraltete Features in PHP 7.0.x
    • Geänderte Funktionen
    • Neue Funktionen
    • Neue Klassen und Interfaces
    • Neue globale Konstanten
    • Änderungen in SAPI-Modulen
    • Entfernte Erweiterungen und SAPIs
    • Sonstige Änderungen
  • Migration von PHP 5.5.x auf PHP 5.6.x
    • Nicht abwärtskompatible Änderungen
    • Neue Features
    • Missbilligte Features in PHP 5.6.x
    • Geänderte Funktionen
    • Neue Funktionen
    • OpenSSL Änderungen in PHP 5.6.x
    • Sonstige Änderungen bei Extensions
    • Neue globale Konstanten
  • PHP Debugging
    • Über Debugging in PHP
  • Konfigurationsoptionen
    • Liste der Kern-Konfigurationsoptionen
  • php.ini Direktiven
    • Liste der php.ini-Direktiven
    • Liste der php.ini-Abschnitte
    • Beschreibung der php.ini-Direktiven des Sprachkerns
  • Extension-Liste/-Kategorisierung
    • Alphabetisch
    • Zugehörigkeit
    • Status
  • Liste der Funktions-Aliase
  • Liste der reservierten Wörter
    • Liste der Schlüsselwörter
    • Vordefinierte Klassen
    • Vordefinierte Konstanten
    • Liste weiterer reservierter Wörter
  • Liste der Ressourcen-Typen
  • Liste verfügarer Filter
    • Filter für Zeichenketten
    • Umwandlungsfilter
    • Komprimierungsfilter
    • Verschlüsselungsfilter
  • Liste der unterstützten Socket-Transporter
    • Internet Domain: TCP, UDP, SSL und TLS
    • Unix-Domain: Unix und UDG
  • Tabelle zu Typenvergleichen in PHP
  • Liste der Parsertoken
  • Userland-Namensregeln
    • Globaler Namensraum
    • Regeln
    • Tipps
  • Über das Handbuch
    • Formate
    • Über die Kommentare (User Notes)
    • Wie man eine Funktionsdefinition (Prototyp) liest
    • In diesem Handbuch beschriebene PHP-Versionen
    • Mehr Informationen über PHP finden
    • Wie man helfen kann, die Dokumentation zu verbessern
    • Wie wir die Formate generieren
    • Übersetzungen
  • Creative Commons Attribution 3.0
  • Verzeichnis der Inhaltsverzeichnisse
    • Funktions- und Methodenverzeichnis
    • Verzeichnis der Beispiele
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


Die Geschichte von PHP und verwandten Projekten

Inhaltsverzeichnis

  • Die Geschichte von PHP
  • Geschichte von PHP verwandten Projekten
  • Bücher über PHP
  • Publikationen über PHP

PHP hat seit seiner Entstehung in der Mitte der 90er Jahre einen langen Weg hinter sich, um zu einer der bekanntesten Sprachen für das Web zu werden, war keine einfache Aufgabe. Wenn Sie daran interessiert sind kurz zu sehen, wie PHP zu dem gewachsen ist was es heute ist, dann lesen Sie weiter. Ältere Versionen von PHP finden Sie im » PHP Museum.

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


Die Geschichte von PHP

PHP Tools, FI, Construction Kit, und PHP/FI

PHP ist der Nachfolger eines älteren Produktes, PHP/FI. PHP/FI wurde 1994 von Rasmus Lerdorf geschaffen. Ursprünglich war PHP/FI ein Set von Common Gateway Interface (CGI) Programmen zur Erfassung der Zugriffe auf seinen Webauftritt. Er nannte dieses Set von Skripten "Personal Home Page Tools", auch bekannt als "PHP Tools". Als dann mehr Funktionalität benötigt wurde, schrieb Rasmus eine viel größere Umsetzung, welche auch mit Datenbanken kommunizieren konnte, und den Benutzern die Entwicklung einfacher dynamischer Webapplikationen, wie Gästebüchern, ermöglichte. Rasmus entschloss sich im Juni 1995, den Sourcecode der PHP Tools zu » veröffentlichen, sodass ihn jeder benutzen, von Fehlern bereinigen, und weiterentwicklen konnte.

Im September dieses Jahres erweiterte Rasmus PHP und verzichtete sogar kurzzeitig auf das PHP im Namen. Nun wurden die Tools FI (kurz für "Formas Interpreter") genannt, und beinhalteten manches an Funktionalität des PHP wie wir es heute kennen. Es besaß Variablen wie in Perl, automatische Interpretation von Formularvariablen und eine in HTML eingebettete Syntax. Die Syntax selbst war der von Perl ähnlich, wenn auch viel eingeschränkter, einfach, und etwas inkonsistent. Tatsächlich mussten HTML-Kommentare verwendet werden, um den Code in eine HTML-Datei einzubetten. Obschon diese Methode nicht überall gut aufgenommen wurde, erfreute sich FI zunehmend an Wachstum und Akzeptanz als CGI-Tool – aber immer noch nicht wirklich als Sprache. Allerdings begann sich das im folgenden Monat zu ändern; im Oktober 1995 veröffentlichte Rasmus ein vollständiges Rewrite des Codes, und nannte es nun kurzzeitig Personal Home Page Construction Kit", und dies wurde als, für damalige Verhältnisse, fortgeschrittenes Skript-Interface angesehen. Die Sprache war absichtlich so gestaltet, dass sie C ähnelte, was die Struktur anging, so dass es leicht von Entwicklern genutzt werden konnte, die mit C, Perl und ähnlichen Sprachen vertraut waren. Soweit war es auf UNIX und POSIX-konforme System beschränkt, aber die Möglichkeit einer Windows NT Implementierung wurde untersucht.

Der Code erhielt eine weitere vollständige Überarbeitung, und im April 1996, führte Rasmus, die Namen der vergangenen Veröffentlichungen kombinierend, PHP/FI ein. Diese Implementierung der zweiten Generation war der Beginn der Entwicklung von PHP von einer Sammlung von Tools in eine richtige Programmiersprache. Es enthielt eingebaute Unterstützung für DBM, mSQL und Postgres95 Datenbanken, Cookies, benutzerdefinierte Funktionen und vieles mehr. PHP/FI 2.0 wurde im November 1997 offiziell freigegeben, nachdem es die meiste Zeit seines Lebenszyklus als verschiedene Betaversionen verbracht hatte.

Obwohl es nur für eine kurze Zeit entwickelt wurde, erfreute es sich zunehmend wachsender Beliebtheit in der noch immer jungen Welt der Web-Entwicklung. In 1997 und 1998 war PHP/FI Kult für mehrere Tausend Nutzer auf der ganzen Welt. Eine Netcraft-Erhebung von Mai 1998 zeigte an, dass nahezu 60.000 Domains HTTP-Header mit dem Inhalt "PHP" versandten, was bedeutete, dass der Host-Server es tatsächlich installiert hatte. Diese Zahl war zu dieser Zeit mit ungefähr 1% aller Domains im Internet gleichzusetzen. Trotz dieser eindrucksvollen Zahlen, stand das weitere Reifen von PHP/FI unter schwierigen vorzeichen, da es im Wesentlichen noch immer von einem Individuum entwickelt wurde.

Beispiel #1 PHP/FI Code-Beispiel

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  He, sie verwenden Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Pardon, dieser Datensatz ist nicht vorhanden<p>
<!--endif exit-->
  Willkommen <!--$user-->!<p>
  Sie haben auf ihrem Konto <!--$index:0--> Credits übrig.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 war die erste Version, die dem heutigen PHP gleicht. Da sie PHP/FI 2.0 noch immer uneffizient fanden, und Features vermissten, die sie für eine eCommerce-Anwendung benötigten, die sie für ein Universitätsprojekt entwickelten, begannen Andi Gutmans und Zeev Suraski aus Tel Aviv, Israel, 1997 ein weiteres vollständiges Rewrite des unterliegenden Parsers. Sie kontaktierten Rasmus online, und diskutierten diverse Aspekte der aktuellen Implementierung und ihrer Neuentwicklung von PHP. Im Bestreben die Engine zu verbessern, und auf der Basis der bestehenden Benutzer von PHP/FI aufbauend, entschieden sich Andi, Rasmus und Zeev zur Kooperation, um eine neue unabhängige Programmiersprache zu entwickeln. Die gesamte neue Sprache wurde unter einem neuen Namen veröffentlicht, welche die im Namen PHP/FI 2.0 vorhandene Implizierung einer eingeschränkten persönlichen Nutzung beseitigte. Es wurde einfach 'PHP' genannt, ein rekursives Akronym für PHP: Hypertext Preprocessor.

Eine der größten Stärken von PHP 3.0 waren die starken Erweiterungsmöglichkeiten. Zusätzlich zu der soliden Infrastruktur für eine Menge an Datenbanken, Protokollen und APIs, lockten vor allem die Erweiterungsmöglichkeiten von PHP 3 dutzende von Entwicklern an, welche sich beteiligten, und neue Erweiterungsmodule einbrachten. Möglicherweise war das der Schlüssel zu dem gewaltigen Erfolg von PHP 3.0. Weitere besondere Merkmale von PHP 3.0 waren die Unterstützung für objektorientierte Syntax und die viel bessere sowie konsistentere Sprachsyntax.

Im Juni 1998, mit vielen neuen Entwicklern aus der ganzen Welt, die sich dem Einsatz angeschlossen hatten, wurde PHP 3.0 vom neuen PHP-Entwicklungsteam als offizieller Nachfolger für PHP/FI 2.0 angekündigt. Die aktive Entwicklung von PHP/FI 2.0, die von November des Vorjahres an weitgehend eingestellt worden war, wurde nun offiziell beendet. Nach einer ungefähr neunmonatigen öffentlichen Testphase wurde PHP 3.0 offiziell freigegeben. Zu dieser Zeit war es bereits auf über 70.000 Domains in der ganzen Welt installiert, und nicht länger auf POSIX-konforme Betriebssysteme beschränkt. Ein eher kleiner Anteil der Domains, die PHP als installiert angaben, waren auf Servern gehostet, die unter Windows 95, 98 und NT liefen, bzw. auf Macintosh-Rechnern. An seinem Höhepunkt war PHP 3.0 auf etwa 10% der Webserver im Internet installiert.

PHP 4

Im Winter 1998, kurz nach der offiziellen Freigabe von PHP 3.0, begannen Andi Gutmans und Zeev Suraski den Kern von PHP umzuschreiben. Die Ziele waren eine verbesserte Leistung von komplexen Applikationen, und eine verbesserte Modularität des Code-Basis. Solche Applikationen wurden durch die neuen Leistungsmerkmale von PHP 3.0, der Unterstützung einer großen Auswahl von Datenbanken und APIs von Drittanbietern möglich gemacht, aber PHP 3.0 war nicht dafür entworfen, solche komplexen Applikationen auch effizient zu handhaben.

Die neue Engine, tituliert als 'Zend Engine' (aus den Vornamen Zeev und Andi gebildet), entsprach diesen Zielen im Design erfolgreich, und wurde zum ersten Mal Mitte 1999 eingeführt. PHP 4.0, das auf dieser Engine, verbunden mit einer großen Auswahl an zusätzlichen Leistungsmerkmalen basiert, wurde im Mai 2000 offiziell freigegeben, fast zwei Jahre nach seinem Vorgänger PHP 3.0. Zusätzlich zu der stark verbesserten Leistung, inkludierte PHP 4.0 andere wichtige Leistungsmerkmale, wie Unterstützung für viele weitere Webserver, HTTP-Sessions, Ausgabepufferung, sicherere Wege im Umgang mit Benutzereingaben, und verschiedene neue Sprachkonstrukte.

PHP 5

PHP 5 wurde im Juli 2004 nach langer Entwicklung und mehreren Pre-Releases veröffentlicht. Der Kern von PHP 5 ist die Zend Engine 2.0, die ein neues Objektmodell und Dutzende anderer neuer Features einführt.

Das Entwicklerteam von PHP besteht aus Dutzenden von Entwicklern, ergänzt durch Dutzende von weiteren Personen, die an verwandten Projekten wie PEAR, PECL, der Dokumentation, und einer Netzwerkinfrastruktur von gut über einhundert individuellen Webservern auf sechs der sieben Kontinente, arbeiten. Obgleich nur eine Schätzung basierend auf Statistiken der vergangenen Jahre, kann man gewiss davon ausgehen, dass PHP nun auf dutzenden oder vielleicht sogar hunderten von Millionen Domains in der ganzen Welt installiert ist.

User Contributed Notes

There are no user contributed notes for this page.


Geschichte von PHP verwandten Projekten

PEAR

» PEAR, das PHP Extension and Application Repository (ursprünglich PHP Extension and Add-on Repository) ist PHP's Version von fundamentalen Klassen, und könnte in der Zukunft zu einem der Hauptwege zur Verteilung von PHP Erweiterungen unter Entwicklern werden.

PEAR entstand in Diskussionen während des PHP Developers' Meeting (PDM) vom Januar 2000 in Tel Aviv. Es wurde von Stig S. Bakken geschaffen, und ist seiner erstgeborenen Tochter, Malin Bakken, gewidmet.

Seit Anfang 2000 ist PEAR zu einem großen, signifikanten Projekt mit vielen Entwicklern gewachsen, welche an der Implementierung von gemeinsamer, wiederverwendbarer Funktionalität zum Nutzen der gesamten PHP Gemeinschaft arbeiten. PEAR umfasst heute eine große Auswahl an infrastrukturellen Basisklassen für Datenbankzugriff, Zwischenspeicherung von Inhalten, mathematischen Berechnungen, eCommerce, und viel mehr.

Weitere Informationen zu PEAR sind im » PEAR Manual zu finden.

PHP Initiative zur Qualitätssicherung

Die » PHP Initiative zur Qualitätssicherung wurde im Sommer 2000 als Reaktion auf die Kritik, dass PHP Releases für Produktionssysteme nicht genügend getestet würden, gestartet. Das Team besteht nun aus einer Hauptgruppe von Entwicklern mit einem guten Verständnis der PHP Codebasis. Diese Entwickler stecken eine Menge ihrer Zeit in das auffinden und Beheben von Fehlern in PHP. Zusätzlich gibt es noch viele andere Teammitglieder, die diese Fehlerbehebungen auf den verschiedensten Plattformen testen, und Feedback geben.

PHP-GTK

» PHP-GTK ist die Lösung von PHP, um clientseitige GUI Applikationen zu schreiben. Andrei Zmievski erinnert sich an die Planungs- und Erstellungsphase von PHP-GTK:

GUI Programmierung hat mich immer schon interessiert und ich fand, dass Gtk+ ein sehr nettes Werkzeug ist, außer dass dessen Programmierung in C etwas langwierig ist. Nachdem ich die Implementierungen von PyGtk und GTK-Perl miterlebt habe, entschied ich mich zu sehen, ob PHP ebenfalls mit Gtk+ verbunden werden könnte, wenn auch minimal. Ab August 2000 hatte ich etwas mehr Freizeit, und begann zu experimentieren. Meine Hauptvorlage war die PyGTK Implementierung, denn sie war von den Leistungsmerkmalen her ziemlich komplett, und hatte eine nette objektorientierte Schnittstelle. James Henstridge, der Autor von PyGtk, stand bei diesen ersten Schritten mit hilfreichen Rat zur Seite.

Die Schnittstellen zu all den Gtk+ Funktionen per Hand zu schreiben kam nicht in Frage, und so griff ich die Idee eines Code Generators auf, ähnlich wie es PyGTK tat. Der Code Generator ist ein PHP Programm, das eine Reihe von .defs Dateien mit den Gtk+ Klassen, Konstanten und Information über Methoden liest, und danach C Code generiert, der PHP mit ihnen verbindet. Was nicht automatisch generiert werden kann, wird händisch in eine .overrides Datei geschrieben.

Die Arbeit an dem Code Generator und der Infrastruktur dauerte einige Zeit, da ich im Herbst 2000 nur wenig Zeit für die Arbeit an PHP-GTK erübrigen konnte. Nachdem ich PHP-GTK Frank Kromann gezeigt hatte, bekam er Interesse, und begann mir bei der Arbeit am Code Generator und der Win32 Implementierung zu helfen. Es war richtig aufregend, als wir das erste Hello World Programm schrieben und laufen ließen. Es dauerte noch einige Monate, bis wir das Projekt in einen vorzeigbaren Zustand brachten und am 1. März 2001 die erste Version freigeben konnten. Die Geschichte schlug prompt bei SlashDot ein.

In dem Gefühl, dass PHP-GTK umfangreich werden könnte, habe ich extra Mailinglisten und CVS Repositories dafür eingerichtet, wie auch mit Hilfe von Colin Viebrock die Website gtk.php.net. Die Dokumentation musste ebenfalls erstellt werden, und James Moore begann hierbei zu helfen.

Seit seiner Freigabe gewinnt PHP-GTK an Popularität. Wir haben unser eigenes Dokumentationsteam, das Handbuch wird weiter verbessert, die Leute beginnen Erweiterungen für PHP-GTK, und auch immer mehr Applikationen mit PHP-GTK zu schreiben.

User Contributed Notes

There are no user contributed notes for this page.


Bücher über PHP

Mit dem Wachsen von PHP, wurde es auch zunehmend als weltweit populäre Entwicklungsplattform anzuerkennen. Eine der Interessantesten Arten dies zu sehen war, die im Laufe der Jahre erscheinenden Bücher über PHP zu beobachten.

Unseres Wissens nach was das erste Buch über PHP 'PHP - tvorba interaktivních internetových aplikací' (PHP - Creating Interactive Internet Applications), ein im im April 1999 erschienenes, von Jirka Kosek geschriebenes tschechisches Buch. Ein Monat später folgte ein von Egon Schmid, Christian Cartus und Richard Blume verfasstes deutsches Buch. Das erste englischsprachige Buch über PHP wurde kurz danach veröffentlicht, es war 'Core PHP Programming' von Leon Atkinson. Diese Bücher behandelten PHP 3.0.

Nachdem diese Bücher die ersten ihrer Art waren, folgte schnell eine große Anzahl Bücher von einer Menge Autoren und Verlegern. Es gibt über 400 englischsprachige Bücher, über 100 Bücher in Deutsch, und über 50 Bücher in Französisch oder Spanisch! Weiterhin gibt es Bücher über PHP in vielen anderen Sprachen, wie Koreanisch, Japanisch und Hebräisch.

Diese große Anzahl von Büchern, die von verschiedenen Autoren geschrieben, und vielen Verlegern veröffentlicht wurden, sowie deren Verfügbarkeit in so vielen Sprachen sind ein guter Beleg für den weltweiten Erfolg von PHP.

User Contributed Notes

There are no user contributed notes for this page.


Publikationen über PHP

Soweit wir wissen, erschien der erste Artikel über PHP in einem gedruckten Magazin gegen Ende 1998 in der tschechischen Ausgabe der Computerworld, und behandelte PHP 3.0. Wie auch bei den Büchern war dieser der erste von einer ganzen Serie von Artikeln über PHP, welche in verschiedenen populären Magazinen erschienen sind.

Artikel über PHP erschienen in Dr. Dobbs, Linux Enterprise, Linux Magazine und vielen mehr. Artikel über die Migration von ASP-basierten Applikationen nach PHP unter Windows tauchen sogar in Microsoft's eigenem MSDN auf!

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 8.2.x auf PHP 8.3.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Klassen und Schnittstellen
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Sonstige Änderungen
  • Windows-Unterstützung

Diese neue Minor-Version bringt eine Reihe von neuen Features und ein paar wenige Inkompatibilitäten, die vor einem Wechsel der PHP-Version in Produktivumgebungen getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 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.


Neue Features

PHP-Kern

Ergänzungen beim Schreibschutz (Readonly)

Anonyme Klassen können nun als readonly markiert werden.

Readonly-Eigenschaften können nun beim Klonen reinitialisiert werden.

Typisierte Klassenkonstanten

Klassen-, Interface-, Trait- und Enum-Konstanten können nun typisiert deklariert werden.

Aus magischen Methoden erzeugte Closures

Aus magischen Methoden erzeugte Closures können nun benannte Argumente akzeptieren.

Der Modifikator final bei einer Methode aus einem Trait

Wenn eine Methode aus einem Trait verwendet wird, kann sie nun als final gekennzeichnet werden.

Das Attribut Override

Das Attribut #[\Override] wurde hinzugefügt, damit überprüft wird, ob eine Methode in einer übergeordneten Klasse oder einer implementierten Schnittstelle existiert.

Syntax für das dynamische Abrufen von Klassenkonstanten

Mit der Syntax C::{$name} kann nun dynamisch auf Klassenkonstanten zugegriffen werden.

Initialisierung statischer Variablen

Für die Initialisierung statischer Variablen können nun beliebige Ausdrücke verwendet werden.

Syntax für Fallback-Werte bei ini-Variablen

In ini-Dateien wird nun die Syntax für Fallback-/Standardwerte unterstützt.

<?php
/*
Angenommen, die Datei /pfad/zu/user.ini enthält die folgenden Einstellungen:

listen = localhost:${DRUPAL_FPM_PORT:-9000}
*/

$user_ini = parse_ini_file('/pfad/zu/user.ini');
echo $user_ini['listen']; // localhost:9000

CLI

Die Überprüfung der Syntax (Lint) kann nun bei mehreren Dateien gleichzeitig durchgeführt werden.

DOM

Die Eigenschaften DOMElement::$className und DOMElement::$id wurden hinzugefügt. Diese sind im Moment wegen der Einschränkungen der zugrundeliegenden libxml2 nicht binärsicher. Das bedeutet, dass die Werte der Eigenschaften an einem NUL-Byte abgeschnitten werden.

Die Eigenschaften DOMNode::$isConnected und DOMNameSpaceNode::$isConnected wurden hinzugefügt.

Die Eigenschaften DOMNode::$parentElement und DOMNameSpaceNode::$parentElement wurden hinzugefügt.

FFI

Es ist nun möglich, FFI\CData anderen FFI\CData zuzuweisen. Das bedeutet, dass CData nun Strukturen und Feldern zugewiesen werden kann.

Opcache

opcache_get_status()['scripts'][n]['revalidate'] enthält nun einen Unix-Zeitstempel, der angibt, wann das Skript das nächste Mal revalidiert werden muss. Dies wird durch die INI-Direktive opcache.revalidate_freq festgelegt.

POSIX

posix_getrlimit() akzeptiert nun einen optionalen $res-Parameter, um ein einzelnes Ressourcenlimit abrufen zu können.

posix_isatty() folgt nun der normalen Semantik der Parameterauswertung (ZPP) und gibt eine Typ-Warnung für Integer-Werte aus.

posix_ttyname() folgt nun der normalen Semantik der Parameterauswertung (ZPP) und gibt eine Typ-Warnung für Integer-Werte aus. Darüber hinaus wird nun für Integer-Werte ungültiger Dateideskriptoren eine Wert-Warnung ausgegeben.

Streams

Streams können nun die Benachrichtigung STREAM_NOTIFY_COMPLETED senden. Dies war bisher nicht implementiert.

User Contributed Notes

There are no user contributed notes for this page.


Neue Klassen und Schnittstellen

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.


Neue Funktionen

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.


Neue globale Konstanten

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

Die folgenden Socket-Optionen sind nun definiert, sofern sie unterstützt werden:

  • 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 als Standardwert für
ZipArchive::addFile() und
ZipArchive::replaceFile()
  • ZipArchive::LENGTH_UNCHECKED (libzip >= 1.10)

User Contributed Notes

There are no user contributed notes for this page.


Nicht abwärtskompatible Änderungen

PHP-Kern

Programme, die beinahe zum Stapelüberlauf geführt hätten

Programme, die sehr nahe daran waren, einen Überlauf des Aufrufstapels zu verursachen, können nun einen Error werfen, wenn sie mehr als zend.max_allowed_stack_size-zend.reserved_stack_size Bytes des Stapels verwenden (fiber.stack_size-zend.reserved_stack_size bei Fibers).

Mehrmaliges Ausführen von proc_get_status()

Die Funktion proc_get_status() gibt auf POSIX-Systemen nun immer den richtigen Wert zurück, wenn sie mehrfach ausgeführt wird. Zuvor lieferte nur der erste Aufruf den richtigen Wert. Auch proc_close() gibt nun den richtigen Exit-Code zurück, wenn es nach proc_get_status() ausgeführt wird. Zuvor wurde in diesem Fall -1 zurückgegeben. Intern funktioniert dies, indem das Ergebnis auf POSIX-Systemen zwischengespeichert wird. Wenn das vorherige Verhalten benötigt wird, kann der Schlüssel "cached" in dem von proc_get_status() zurückgegebenen Array überprüft werden, um zu sehen, ob das Ergebnis zwischengespeichert wurde.

Zend-Timer für die maximale Ausführungsdauer

Die Zend-Timer für die maximale Ausführungsdauer (Zend Max Execution Timers) sind nun standardmäßig für ZTS-Builds unter Linux aktiviert.

Verwendung von Traits mit statischen Eigenschaften

Wenn Traits mit statischen Eigenschaften verwendet werden, werden nun die von der Elternklasse geerbten statischen Eigenschaften neu deklariert. Dadurch wird für die aktuelle Klasse ein separater Speicher für statische Eigenschaften angelegt. Dies ist vergleichbar mit dem direkten Hinzufügen statischer Eigenschaften zur Klasse ohne Traits.

Zuweisung eines negativen Indexes an ein leeres Array

Wenn einem leeren Array ein negativer Index $n zugewiesen wird, ist der nächste Index nun immer $n+1 anstelle von 0.

Überprüfung von Klassenkonstanten auf Sichtbarkeitsabweichungen

Wenn eine Klassenkonstante von einer Schnittstelle geerbt wird, wird diese nun korrekt auf Abweichung bei der Sichtbarkeit geprüft.

WeakMap-Einträge, deren Schlüssel auf sich selbst verweisen

Wenn der Schlüssel eines WeakMap-Eintrags auf sich selbst verweist (möglicherweise transitiv) und nur durch Iteration über die WeakMap erreichbar ist (die Erreichbarkeit durch Iteration wird als schwach angesehen), kann dieser Eintrag nun während der Sammlung von Zyklen entfernt werden. Zuvor wurden solche Einträge nie automatisch entfernt.

Date

Für die DateTime-Erweiterung wurden unter den Hierarchien DateError und DateException erweiterungsspezifische Fehler und Exceptions eingeführt, die Warnungen und generische Exceptions ersetzen. Dies verbessert die Fehlerbehandlung, erfordert aber eine Überprüfung auf Fehler und Exceptions.

DOM

Der Aufruf von DOMChildNode::after(), DOMChildNode::before() und DOMChildNode::replaceWith() auf einem Knoten, der kein Elternteil hat, ist nun eine Nulloperation (bewirkt nichts), anstatt eine Hierarchie-Exception zu werfen, was dem von der DOM-Spezifikation geforderten Verhalten entspricht.

Die Methoden DOMParentNode und DOMChildNode können nun auch ohne ein Dokument verwendet werden, ohne dass eine DOM_HIERARCHY_REQUEST_ERR-DOMException geworfen wird. Dies entspricht dem von der DOM-Spezifikation geforderten Verhalten.

Wenn DOMDocument::createAttributeNS() ohne die Angabe eines Präfixes aufgerufen wurde, wurde fälschlicherweise ein Standard-Namensraum erstellt und das Element in den Namensraum statt in das Attribut eingefügt. Dieser Fehler ist nun behoben.

Wenn ein Präfix bereits für einen anderen URI verwendet wurde, hat DOMDocument::createAttributeNS() bisher fälschlicherweise eine DOM_NAMESPACE_ERRNAMESPACE_ERR-DOMException geworfen. Nun wird bei einem Konflikt mit dem Präfixnamen korrekterweise ein anderes Präfix gewählt.

Zu einigen DOM-Klassen wurden neue Methoden und Eigenschaften hinzugefügt. Wenn eine benutzerdefinierte Klasse von diesen Klassen erbt und eine Methode oder Eigenschaft mit dem gleichen Namen deklariert, müssen die Deklarationen kompatibel sein. Andernfalls führt dies zu einem typischen Kompilierfehler wegen inkompatibler Deklarationen. Informationen über die neu implementierten Methoden und Eigenschaften sind in den Listen der neuen Features und neuen Funktionen zu finden.

FFI

C-Funktionen, die den Rückgabetyp void haben, geben nun null anstelle des Objekts object(FFI\CData:void) { } zurück

Opcache

Die INI-Direktive opcache.consistency_checks wurde entfernt. Dieses Feature war sowohl in Verbindung mit dem Tracing-JIT als auch mit dem Vererbungscache defekt und ist seit PHP 8.1.18 und PHP 8.2.5 deaktiviert, ohne dass es eine Möglichkeit gibt, es zu aktivieren. Sowohl das Tracing-JIT als auch der Vererbungscache können den gemeinsamen Speicher (shm) verändern, nachdem das Skript persistent gemacht wurde, indem sie seine Prüfsumme ungültig machen. Die geplante Korrektur sah vor, die veränderbaren Zeiger zu überspringen, wurde aber aufgrund der Komplexität verworfen. Daher wurde stattdessen beschlossen, diese Funktion zu entfernen.

Phar

Der Typ der Phar-Klassenkonstanten wird nun deklariert.

Standard

An der Funktion range() wurden mehrere Änderungen vorgenommen:

  • Wenn Objekte, Ressourcen oder Arrays als begrenzende Werte übergeben werden, wird nun ein TypeError geworfen.
  • Wenn für $step 0 übergeben wird, wird ein aussagekräftigerer ValueError geworfen.
  • Wenn ein negativer von $step für steigende Bereiche verwendet wird, wird nun ein ValueError geworfen.
  • Wenn $step eine Gleitkommazahl ist, die als Ganzzahl interpretiert werden kann, wird sie nun als solche behandelt.
  • Wenn ein Argument unendlich oder NAN ist, wird nun ein ValueError geworfen.
  • Wenn $start oder $end eine leere Zeichenkette ist, wird nun ein E_WARNING ausgegeben. Der Wert wird weiterhin in den Wert 0 umgewandelt.
  • Wenn start oder end eine nicht-numerische Zeichenkette mit mehr als einem Byte ist, wird nun ein E_WARNING ausgegeben.
  • Wenn start oder end eine Zeichenkette ist, die implizit in eine Ganzzahl umgewandelt wird, weil der andere begrenzende Werte eine Zahl ist (z. B. range(5, 'z');), wird nun ein E_WARNING ausgegeben.
  • Wenn $step eine Gleitkommazahl ist, wird nun ein E_WARNING ausgegeben, wenn versucht wird, einen Bereich von Zeichen zu erzeugen, es sei denn, beide begrenzenden Werte sind numerische Zeichenketten (z. B. verursacht range('5', '9', 0.5); keine Warnung).
  • Die Funktion number_format() verarbeitet nun negative $decimals-Werte, indem $num auf abs($decimals) Ziffern vor dem Dezimaltrennzeichen gerundet wird; zuvor wurden negative $decimals-Werte ignoriert.
  • Wenn einer der begrenzenden Werte eine Ziffer in Form einer Zeichenkette ist (z. B. range('9', 'A');), erzeugt range() nun eine Liste von Zeichen, anstatt den anderen Wert in eine Ganzzahl umzuwandeln.
<?php
range('9', 'A'); // ["9", ":", ";", "<", "=", ">", "?", "@", "A"], seit PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], vor PHP 8.3.0
?>

Die Flags-Fehlerprüfung der Funktion file() fängt nun alle ungültigen Flags ab. Insbesondere FILE_APPEND wurde bisher stillschweigend akzeptiert.

SNMP

Der Typ der SNMP-Klassenkonstanten wird nun deklariert.

User Contributed Notes

There are no user contributed notes for this page.


Veraltete Features

PHP-Kern

Änderungen bei Inkrement-/Dekrement-Operatoren

Die Verwendung des Inkrement-Operators (++) für leere, nicht-numerische oder nicht-alphanumerische Zeichenketten ist nun veraltet. Darüber hinaus wird das Inkrementieren nicht-numerischer Zeichenketten als sanft veraltet ("soft deprecated") eingestuft. "Soft deprecated" bedeutet, dass zwar keine E_DEPRECATED-Diagnose ausgegeben wird, aber dieses Feature in neuem Code nicht mehr verwendet werden sollte. Stattdessen sollte die neue Funktion str_increment() verwendet werden.

Die Verwendung des Dekrement-Operators (--) für leere oder nicht-numerische Zeichenketten ist nun veraltet.

Aufruf von get_class()/get_parent_class() ohne Argumente

Der Aufruf von get_class() und get_parent_class() ohne Argumente ist nun veraltet.

DBA

Der Aufruf von dba_fetch() mit $dba als drittes Argument ist nun veraltet.

FFI

Der statische Aufruf der Methoden FFI::cast(), FFI::new() und FFI::type() ist nun veraltet.

Intl

Die Konstante U_MULTIPLE_DECIMAL_SEP*E*RATORS ist veraltet, stattdessen sollte die Konstante U_MULTIPLE_DECIMAL_SEP*A*RATORS verwendet werden.

Die Konstante NumberFormatter::TYPE_CURRENCY ist veraltet.

LDAP

Der Aufruf von ldap_connect() mit getrenntem $hostname und $port ist veraltet.

MBString

Bei mb_strimwidth() ist die Übergabe eines negativen Wertes für den Parameter $width nun veraltet.

Phar

Der Aufruf der Methode Phar::setStub() mit einer Ressource und dem Parameter $length ist nun veraltet. Solche Aufrufe sollten durch $phar->setStub(stream_get_contents($resource)); ersetzt werden.

Random

Die MT_RAND_PHP-Variante Mt19937 ist veraltet.

Reflection

Der Aufruf von ReflectionProperty::setValue() mit nur einem Parameter ist veraltet. Um statische Eigenschaften zu setzen, sollte null als erster Parameter übergeben werden.

Standard

Die Funktion assert_options() ist nun veraltet.

Die Konstanten ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION und ASSERT_WARNING sind veraltet.

Die INI-Einstellungen assert.* sind veraltet. Weitere Informationen hierzu sind auf der Seite Änderungen bei der Handhabung von INI-Dateien zu finden.

SQLite3

Da die Warnungen in Zukunft entfernt werden, sollten nun vorzugsweise Exceptions verwendet werden. Der Aufruf von SQLite3::enableExceptions(false) ist veraltet und führt in dieser Version zu einer entsprechenden Warnung.

Zip

Die Konstante ZipArchive::FL_RECOMPRESS ist veraltet und wird in einer zukünftigen libzip-Version entfernt.

User Contributed Notes

There are no user contributed notes for this page.


Sonstige Änderungen

PHP-Kern

FFI

Die Methode FFI::load() kann nun während des Preloads aufgerufen werden, wenn opcache.preload_user der aktuelle Systembenutzer ist. Zuvor war der Aufruf von FFI::load() während des Preloads nicht möglich, wenn die Direktive opcache.preload_user gesetzt war.

FPM

Der FPM CLI-Test schlägt nun fehl, wenn der Socket-Pfad länger ist als vom Betriebssystem unterstützt.

Opcache

In den SAPIs CLI und phpdbg muss die Direktive opcache.preload_user nicht mehr für das Preloading gesetzt werden, wenn sie als root ausgeführt werden. In anderen SAPIs ist diese Direktive weiterhin erforderlich, wenn sie als root ausgeführt werden, weil das Preloading durchgeführt wird, bevor die SAPI zu einem unprivilegierten Benutzer wechselt.

Streams

Wenn die Funktion fread() auf einer Socket-Verbindung blockiert wird und gepufferte Daten vorhanden sind, gibt sie diese sofort zurück, statt auf weitere Daten zu warten.

Ein Speicherstrom schlägt nicht mehr fehl, wenn der Such-Offset über das Ende hinausgeht. Stattdessen wird der Speicher beim nächsten Schreibvorgang vergrößert und der Bereich zwischen dem alten Ende und dem Offset wird mit Nullbytes gefüllt, ähnlich wie es auch bei Dateien der Fall ist.

stat()-Zugriffsoperationen wie file_exists() und ähnliche verwenden nun den tatsächlichen Pfad statt des aktuellen Stream-Pfads, was mit dem Öffnen von Streams übereinstimmt.

Änderungen in SAPI-Modulen

CLI

Die STDOUT-, STDERR- und STDIN-Streams werden nicht mehr geschlossen, wenn die Ressource zerstört wird, was in der Regel beim Beenden der CLI der Fall ist. Es ist jedoch immer noch möglich, diese Streams mittels fclose() und ähnlichem explizit zu schließen.

Geänderte Funktionen

PHP-Kern

Bei der Funktion gc_status() wurden die folgenden 8 Felder hinzugefügt:

  • "running" => bool
  • "protected" => bool
  • "full" => bool
  • "buffer_size" => int
  • "application_time" => float: die gesamte Ausführungszeit der Anwendung in Sekunden (einschließlich collector_time)
  • "collector_time" =>float: die Zeit, die mit dem Sammeln von Zyklen verbracht wurde, in Sekunden (einschließlich destructor_time und free_time)
  • "destructor_time" => float: die Zeit, die während des Sammelns von Zyklen für die Ausführung von Destruktoren benötigt wurde, in Sekunden
  • "free_time" => float: die Zeit, die während des Sammelns von Zyklen dafür benötigt wurde, Speicher freizugeben, in Sekunden

Mit der Funktion class_alias() kann nun ein Alias einer internen Klasse erstellt werden.

Wenn open_basedir zur Laufzeit mittels ini_set('open_basedir', ...); gesetzt wird, werden keine Pfade mehr akzeptiert, die das übergeordnete Verzeichnis (..) enthalten; zuvor waren nur die Pfade unzulässig, die mit .. beginnen. Dies konnte leicht umgangen werden, indem dem Pfad ./ vorangestellt wurde.

Benutzerdefinierte Exception-Handler fangen nun Exceptions beim Herunterfahren ab.

Die HTML-Ausgabe der Funktionen highlight_string() und highlight_file() wurde geändert. Leerzeichen zwischen äußeren HTML-Tags werden entfernt. Zeilenumbrüche und Leerzeichen werden nicht mehr in HTML-Entities umgewandelt. Der gesamte HTML-Text wird nun in <pre>-Tags eingeschlossen. Die äußeren <span>-Tags wurden mit den <code>-Tags verschmolzen.

Calendar

Die Funktion easter_date() unterstützt nun auf 64-Bit-Systemen die Jahreszahlen von 1970 bis 2.000.000.000; bisher wurden nur die Jahre im Bereich von 1970 bis 2037 unterstützt.

Curl

Die Funktion curl_getinfo() unterstützt nun zwei neue Konstanten: CURLINFO_CAPATH und CURLINFO_CAINFO. Wenn der Wert des Parameters option null ist, stehen die zwei zusätzlichen Schlüssel "capath" und "cainfo" zur Verfügung.

DOM

Der voreingestellte Rückgabetyp der Methode DOMCharacterData::appendData() wurde auf true geändert.

Der voreingestellte Rückgabetyp der Methoden DOMDocument::loadHTML(), DOMDocument::loadHTMLFile() und DOMDocument::loadXML() ist nun bool. Zuvor war dies mit dem Rückgabetyp DOMDocument|bool dokumentiert, aber seit PHP 8.0.0 kann ein Objekt der Klasse DOMDocument nicht mehr zurückgegeben werden, da es nicht mehr statisch aufgerufen werden kann.

Gd

Die Signatur der Funktion imagerotate() wurde geändert. Der Parameter $ignore_transparent wurde entfernt, da er seit PHP 5.5.0 ignoriert wurde.

Intl

Die Funktion datefmt_set_timezone() und ihr Alias, die Methode IntlDateformatter::setTimeZone(), geben nun bei Erfolg true zurück; zuvor wurde null zurückgegeben.

Die Methode IntlBreakiterator::setText() gibt nun bei Erfolg true und bei einem Fehler false zurück; zuvor gab sie in beiden Fällen null zurück.

Die Methode IntlChar::enumCharNames() gibt nun einen booleschen Wert zurück; zuvor gab sie bei Erfolg null und bei einem Fehler false zurück.

Die Methode IntlDateFormatter::__construct() wirft eine U_ILLEGAL_ARGUMENT_ERROR-Exception, wenn eine ungültige Locale gesetzt gesetzt wurde.

MBString

Die Funktionen mb_strtolower() und mb_convert_case() implementieren für den griechischen Buchstaben Sigma die Regeln der bedingten Groß- und Kleinschreibung. Bei der Funktion mb_convert_case() gilt die bedingte Groß-/Kleinschreibung nur für die Modi MB_CASE_LOWER und MB_CASE_TITLE, nicht aber für MB_CASE_LOWER_SIMPLE und MB_CASE_TITLE_SIMPLE.

Die Funktion mb_decode_mimeheader() interpretiert Unterstriche in QPrint-kodierten MIME-kodierten Wörtern gemäß RFC 2047 und wandelt sie in Leerzeichen um. Unterstriche müssen in solchen MIME-kodierten Wörtern als "=5F" kodiert werden.

In seltenen Fällen kodiert die Funktion mb_encode_mimeheader() die Eingabezeichenkette um, während sie in PHP 8.2 als reines ASCII durchgereicht würde.

Die Funktion mb_encode_mimeheader() entfernt keine NUL- (Null) Bytes mehr, wenn die Eingabezeichenkette in Qprint-Kodierung vorliegt. Dies führte in früheren Versionen bei bestimmten Textkodierungen, insbesondere UTF-16 und UTF-32, dazu, dass Zeichenketten von mb_encode_mimeheader beschädigt wurden.

Der "non-strict"-Modus der Funktion mb_detect_encoding() verhält sich nun wie in der Dokumentation beschrieben. Zuvor gab sie false zurück, wenn ein bestimmtes Byte (z. B. das Erste) der Eingabezeichenkette in allen möglichen Kodierungen ungültig war. Allgemeiner ausgedrückt: Alle in Frage kommenden Kodierungen, in denen ein solches Byte ungültig war, wurden ausgeschlossen, und wenn dasselbe Byte alle verbleibenden Kodierungen ausschloss, die noch in Frage kamen, wurde false zurückgegeben. Wurden hingegen alle in Frage kommenden Kodierungen bis auf eine ausgeschlossen, wurde die letzte verbleibende Kodierung zurückgegeben, ohne Rücksicht darauf, wie viele Kodierungsfehler später in der Zeichenkette auftreten könnten. Dies unterscheidet sich von dem in der Dokumentation beschriebenen Verhalten, das besagt: "Wenn strict auf false gesetzt ist, wird die am besten passende Kodierung zurückgegeben."

mysqli

Die Funktion mysqli_fetch_object() wirft nun einen ValueError statt einer Exception, wenn das Argument $constructor_args nicht leer ist, die Klasse aber keinen Konstruktor hat.

Die Funktion mysqli_poll() wirft nun einen ValueError, wenn weder das Argument $read noch das Argument $error übergeben wird.

Der Rückgabetyp der Funktion mysqli_field_seek() und der Methode mysqli_result::field_seek() wurde von bool auf true geändert.

ODBC

Die Funktion odbc_autocommit() akzeptiert nun null als Wert für den Parameter $enable. Die Übergabe von null entspricht der Übergabe von nur einem Parameter, d. h. die Funktion zeigt an, ob autocommit aktiviert ist oder nicht.

PGSQL

Die Funktion pg_fetch_object() wirft nun einen ValueError statt einer Exception, wenn das Argument $constructor_args nichtleer ist, die Klasse aber keinen Konstruktor hat.

Die Funktion pg_insert() wirft nun einen ValueError statt eine E_WARNING-Meldung auszugeben, wenn die angegebene Tabelle ungültig ist.

Wenn der Wert/Typ eines Feldes nicht mit dem PostgreSQL-Typ übereinstimmt, werfen die Funktionen pg_insert() und pg_convert() einen ValueError oder einen TypeError, statt eine E_WARNING-Meldung auszugeben.

Bei den Funktionen pg_fetch_result(),
pg_field_prtlen() und
pg_field_is_null() kann der Wert des Parameters
$row nun null sein.

Random

Die Funktionen mt_srand() und srand() prüfen nun nicht mehr die Anzahl der Argumente, um festzustellen, ob ein Zufallswert (Seed) verwendet werden soll. Wenn null übergeben wird, wird ein Seed erzeugt, bei 0 wird Null als Seed verwendet. Damit entspricht das Verhalten dieser Funktionen dem der Methode Random\Engine\Mt19937::__construct().

Reflection

Der Rückgabetyp der Methode ReflectionClass::getStaticProperties() kann nicht mehr null sein.

Standard

Bei der Funktion unserialize() wurden Meldungen der Stufe E_NOTICE auf E_WARNING hochgestuft.

Die Funktion unserialize() gibt nun eine neue Meldung der Stufe E_WARNING aus, wenn nicht alle Bytes der Eingabe verarbeitet wurden.

Die Funktion array_pad() ist nun nur noch durch die maximale Anzahl der Elemente begrenzt, die ein Array haben kann; zuvor konnten nur maximal 1048576 Elemente auf einmal hinzugefügt werden.

Die Funktion strtok() erzeugt eine Meldung der Stufe E_WARNING, wenn beim Start der Tokenisierung kein Token angegeben wird.

Wenn die Erzeugung des Salt fehlschlägt, verkettet die Funktion password_hash() nun die zugrundeliegende Random\RandomException als $previous-Exception der ValueError-Exception.

Wenn ein Array als Parameter $command an die Funktion proc_open() übergeben wird, muss es nun mindestens ein nichtleeres Element enthalten; andernfalls wird ein ValueError geworfen.

Wenn das $command-Array ein ungültiger Befehl ist, gibt die Funktion proc_open() false zurück, statt ein Ressourcenobjekt, das später eine Warnung erzeugt. Dies war unter Windows bereits der Fall und ist nun auch der Fall, wenn eine posix_spawn-Implementierung verwendet wird (die meisten Linux-, BSD- und MacOS-Plattformen). Es gibt noch ein paar alte Plattformen, bei denen sich dieses Verhalten nicht geändert hat, da posix_spawn dort nicht unterstützt wird.

Die Funktionen array_sum() und array_product() geben nun eine Warnung aus, wenn Werte in einem Array nicht in int/float umgewandelt werden können. Zuvor wurden Arrays und Objekte ignoriert, während alle anderen Werte in int umgewandelt wurden. Außerdem werden Objekte, die eine Umwandlung in eine Zahl definieren (z. B. GMP), nun umgewandelt statt ignoriert.

Der Parameter $decimals der Funktion number_format() verarbeitet nun auch negative Zahlen korrekt. Wenn $decimals einen negativen Wert hat, wird $num auf $decimals signifikante Stellen vor dem Dezimaltrennzeichen gerundet. Zuvor wurden negative $decimals stillschweigend ignoriert und die Zahl wurde auf null Dezimalstellen gerundet.

Der Funktion strrchr() wurde der neue Parameter $before_needle hinzugefügt. Er verhält sich wie der entsprechende Parameter der Funktionen strstr() und stristr().

Die Funktionen str_getcsv() und fgetcsv() geben nun für das letzte Feld eine leere Zeichenkette statt einer Zeichenkette mit einem einzelnen Null-Byte zurück, wenn dieses Feld nur eine nicht terminierte Enclosure (Einschließung) enthält.

Sonstige Änderungen bei Erweiterungen

Core

Die Anwendung des Inkrement/Dekrement-Operators (++/--) auf einen Wert vom Typ bool führt nun zu einer Warnung. Der Grund dafür ist, dass dieser Operator zwar derzeit keine Wirkung hat, sich aber in Zukunft wie $bool += 1 verhalten wird.

Die Anwendung des Dekrement-Operators (--) auf einen Wert vom Typ null führt nun zu einer Warnung. Der Grund dafür ist, dass dieser Operator zwar derzeit keine Wirkung hat, sich aber in Zukunft wie $null -= 1 verhalten wird.

Interne Objekte, die die _IS_NUMBER-Umwandlung implementieren, aber keinen do_operator-Handler, der die Addition und Subtraktion überschreibt, können nun inkrementiert und dekrementiert werden, als ob $o += 1 oder $o -= 1 ausgeführt worden wäre.

DOM

Der DOM-Mechanismus zur Verwaltung der Lebensdauer wurde dahingehend überarbeitet, dass implizit gelöschte Knoten weiterhin abgerufen werden können; zuvor führte dies zu einer Exception.

SQLite3

Die Klasse SQLite3 wirft nun eine SQLite3Exception (eine Erweiterung von Exception) statt einer Exception.

Der SQLite-Fehlercode wird nun im Fehlercode der Exception übergeben, statt in der Fehlermeldung enthalten zu sein.

Änderungen bei der Handhabung von INI-Dateien

  • Die assert.*-INI-Direktiven sind veraltet. Dies betrifft die folgenden Direktiven:

    • assert.active
    • assert.bail
    • assert.callback
    • assert.exception
    • assert.warning
    Wenn der Wert einer Direktive mit dem Standardwert übereinstimmt, wird keine Meldung über die Missbilligung ausgegeben. Statt dieser Direktiven sollte die INI-Direktive zend.assertions verwendet werden.

  • zend.max_allowed_stack_size ist eine neue INI-Direktive, mit der die maximal erlaubte Stackgröße festgelegt werden kann; mögliche Werte sind 0 (erkennt die maximale Stackgröße des Prozesses oder Threads), -1 (kein Limit) oder eine positive Anzahl von Bytes. Der Standardwert ist 0. Wenn es nicht möglich ist, die maximale Stackgröße des Prozesses oder Threads zu ermitteln, wird eine bekannte Systemvorgabe verwendet. Wird dieser Wert zu hoch eingestellt, hat das den gleichen Effekt wie die Deaktivierung der Stack-Größenbegrenzung. Fibers verwenden fiber.stack_size als maximal erlaubte Stackgröße. Wenn der Stack des Prozessaufrufs zend.max_allowed_stack_size-zend.reserved_stack_size Bytes überschreitet, wird ein Error geworfen, um Segmentierungsfehler durch Stack-Überlauf zu verhindern und damit die Fehlersuche zu erleichtern. Die Stackgröße erhöht sich während unkontrollierter Rekursionen mit internen Funktionen oder den magischen Methoden __toString(), __clone(), __sleep(), __destruct(). Dies hat nichts mit Stack-Pufferüberläufen zu tun und ist somit auch keine Sicherheitsmaßnahme.

  • zend.reserved_stack_size ist eine neue INI-Direktive, mit der die zu reservierende Stackgröße in Bytes festgelegt werden kann. Wenn die Stackgröße überprüft wird, wird dieser Wert als Puffer von der maximal erlaubten Stackgröße abgezogen.

Performance

DOM

Beim Durchlaufen einer Schleife über eine DOMNodeList wird nun ein Zwischenspeicher verwendet. Dadurch steigt die Zeit, die für die Abfrage von Elementen benötigt wird, nicht mehr standardmäßig quadratisch an.

Wenn Textinhalte von Knoten abgerufen werden, wird nun vermieden, Speicher zuzuweisen, was zu einem Leistungsgewinn führt.

DOMChildNode::remove() läuft nun mit O(1)-Performance.

Standard

Die flags-Fehlerprüfung der Funktion file() ist nun etwa 7% schneller.

SPL

Die Klasse RecursiveDirectoryIterator führt nun weniger I/O (Ein-/Ausgabeoperationen) durch, wenn ein Verzeichnis in einer Schleife durchlaufen wird.

User Contributed Notes

There are no user contributed notes for this page.


Windows-Unterstützung

PHP-Kern

Die niedrigste unterstützte Windows-Version wurde auf Windows 8 oder Windows Server 2012 angehoben.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 8.1.x auf PHP 8.2.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Sonstige Änderungen
  • Windows-Unterstützung

Diese neue Minor-Version bringt eine Reihe von neuen Features und ein paar wenige Inkompatibilitäten, die vor einem Wechsel der PHP-Version in Produktivumgebungen getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

PHP-Kern

Attribut SensitiveParameter

Das Attribut #[\SensitiveParameter] wurde hinzugefügt, um sensible Daten in Backtraces unkenntlich zu machen.

INI-Direktive error_log_mode

Die INI-Direktive error_log_mode wurde hinzugefügt, um die Berechtigungen für die Fehler-Logdatei festlegen zu können.

Eigenschaften von Aufzählungen in konstanten Ausdrücken

Es ist nun möglich, die Eigenschaften von Aufzählungen in konstanten Ausdrücken abzurufen.

Verbesserungen am Typensystem

Es ist nun möglich, null und false als eigenständige Typen zu verwenden.

Der Typ true wurde hinzugefügt.

Es ist nun möglich, Schnittmengentypen (Intersection-Typen) und zusammengefasste Typen (Union-Typen) zu kombinieren. Der Typ muss in DNF geschrieben werden.

Konstanten in Traits

Es ist nun möglich, Konstanten in Traits zu definieren.

Schreibgeschützte Klassen

Klassen können nun als readonly definiert werden.

cURL

Die Option CURLINFO_EFFECTIVE_METHOD wurde hinzugefügt, die die aktuell verwendete HTTP-Methode im Rückgabewert von curl_getinfo() zurückgibt.

Mehrere neue Konstanten von libcurl 7.62 bis 7.80 sind nun verfügbar.

Die Funktion curl_upkeep() wurde hinzugefügt, um Verbindungen aufrechtzuerhalten.

DBA

Der LMDB-Treiber akzeptiert nun die Flags DBA_LMDB_USE_SUB_DIR und DBA_LMDB_NO_SUB_DIR, um zu bestimmen, ob beim Erstellen einer Datenbankdatei ein Unterverzeichnis erstellt werden soll oder nicht.

OCI8

Um die Leistung bei Abfragen von LOBs (Large Objects) zu optimieren, wurden die INI-Direktive oci8.prefetch_lob_size und die Funktion oci_set_prefetch_lob() hinzugefügt. Damit wird die Anzahl der Roundtrips (Kommunikationsvorgänge) zwischen PHP und Oracle-Datenbanken beim Abrufen von LOBs reduziert. Diese Funktion ist mit Oracle Database 12.2 oder höher verwendbar.

OpenSSL

Der Algorithmus chacha20-poly1305 unterstützt nun AEAD.

ODBC

Die Funktionen odbc_connection_string_is_quoted(), odbc_connection_string_should_quote(), und odbc_connection_string_quote() wurden hinzugefügt. Diese werden in den Erweiterungen ODBC und PDO_ODBC hauptsächlich hinter den Kulissen verwendet, sind aber für einfachere Unit-Tests und für Benutzeranwendungen und -bibliotheken zugänglich, um selbst Quoting (in Anführungszeichen setzen) zu verwenden.

PCRE

Die Unterstützung für den Modifikator n (NO_AUTO_CAPTURE) wurde hinzugefügt, wodurch einfache (xyz)-Gruppen nicht erfasst werden. Nur benannte Gruppen wie (?<name>xyz) werden erfasst. Dies wirkt sich nur darauf aus, welche Gruppen erfasst werden. Es ist immer noch möglich, nummerierte Referenzen auf Teile von Suchmustern zu verwenden, und das Array mit den Übereinstimmung enthält immer noch die nummerierten Ergebnisse.

Random

Dies ist eine neue Erweiterung, die bestehende Implementierungen von Zufallszahlengeneratoren organisiert und vereinheitlicht. Es stehen nun neue und bessere Zufallszahlengeneratoren zur Verfügung, bei denen die Probleme mit dem Geltungsbereich behoben wurden.

User Contributed Notes

There are no user contributed notes for this page.


Neue Funktionen

cURL

  • curl_upkeep()

IMAP

  • imap_is_open() (ab PHP 8.2.1)

MySQLi

  • mysqli_execute_query()

ODBC

  • odbc_connection_string_is_quoted()
  • odbc_connection_string_should_quote()
  • odbc_connection_string_quote()

OpenSSL

  • openssl_cipher_key_length()

Reflection

  • ReflectionFunction::isAnonymous()
  • ReflectionMethod::hasPrototype()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20_xor_ic()

Standard

  • memory_reset_peak_usage()
  • ini_parse_quantity()

XML

  • libxml_get_external_entity_loader()

User Contributed Notes

There are no user contributed notes for this page.


Neue globale Konstanten

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

Die folgenden Socket-Optionen sind nun definiert, sofern sie unterstützt werden:

  • SO_INCOMING_CPU
  • SO_MEMINFO
  • SO_RTABLE (OpenBSD)
  • TCP_KEEPALIVE (MacOS)
  • TCP_KEEPCNT (Linux, andere)
  • TCP_KEEPIDLE (Linux, andere)
  • TCP_KEEPINTVL (Linux, andere)
  • 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.


Nicht abwärtskompatible Änderungen

Date

Die Methode DateTime::createFromImmutable() hat nun den vorläufigen Rückgabetyp static, vorher war es DateTime.

Die Methode DateTimeImmutable::createFromMutable() hat nun den vorläufigen Rückgabetyp static, vorher war es DateTimeImmutable.

In relativen Formaten akzeptieren die number-Symbole keine mehrfachen Vorzeichen mehr, z. B. +-2.

ODBC

Die Erweiterung ODBC maskiert nun den Benutzernamen und das Passwort für den Fall, dass sowohl eine Zeichenkette für die Verbindung als auch Benutzername/Passwort übergeben werden und die Zeichenkette angehängt werden muss. Zuvor konnten Benutzerwerte, die zu maskierende Werte enthielten, eine fehlerhafte Verbindungszeichenkette erzeugen oder Werte aus vom Benutzer bereitgestellten Daten injizieren. Die Regeln für die Maskierung sollten mit dem Verhalten der .NET BCL DbConnectionOptions identisch sein.

PDO_ODBC

Wenn eine Zeichenkette für die Verbindung übergeben wird, werden bei der Erweiterung PDO_ODBC auch der Benutzername und das Passwort maskiert. Siehe Änderung an der Erweiterung ODBC für weitere Details.

Standard

Die Funktion glob() gibt nun ein leeres Array zurück, wenn alle Pfade durch open_basedir eingeschränkt sind. Zuvor gab sie false zurück. Außerdem wird nun eine Warnung ausgegeben, auch wenn nur einige Pfade durch open_basedir eingeschränkt sind.

FilesystemIterator::__construct(): Vor PHP 8.2.0 war die Konstante FilesystemIterator::SKIP_DOTS immer gesetzt und konnte nicht deaktiviert werden. Um das bisherige Verhalten beizubehalten, muss die Konstante explizit gesetzt werden, wenn der Parameter flags verwendet wird. Der Standardwert des Parameters flags wurde nicht geändert.

Die Funktionen strtolower(),
strtoupper(),
stristr(),
stripos(),
strripos(),
lcfirst(),
ucfirst(),
ucwords() und str_ireplace()
berücksichtigen die Locale nicht mehr. Sie führen die Umwandlung der Groß-
und Kleinschreibung nun im ASCII-Format durch, als ob die Locale "C" wäre.
Lokalisierte Versionen dieser Funktionen stehen in der Erweiterung
MBString zur Verfügung. Darüber hinaus
verwenden array_change_key_case() und die Sortierung mit
SORT_FLAG_CASE nun ebenfalls die Umwandlung von Groß-
und Kleinschreibung im ASCII-Format.

Die Funktion str_split() gibt bei einer leeren Zeichenkette nun ein leeres Array zurück. Zuvor gab sie in diesem Fall ein Array mit einem einzigen leeren Eintrag für die Zeichenkette zurück. Die Funktion mb_str_split() ist von dieser Änderung nicht betroffen, weil sie sich schon vorher so verhalten hat.

Die Funktionen ksort() und krsort() führen Vergleiche von numerischen Zeichenketten nun gemäß SORT_REGULAR durch und verwenden dabei die Standardregeln von PHP 8.

Die Funktion var_export() lässt bei exportierten Klassennamen den vorangestellten Backslash nicht mehr weg, d. h. diese sind nun voll qualifiziert.

Standard-PHP-Bibliothek (SPL)

Die folgenden Methoden erzwingen nun ihre Signatur:

  • SplFileInfo::_bad_state_ex()
  • SplFileObject::getCsvControl()
  • SplFileObject::fflush()
  • SplFileObject::ftell()
  • SplFileObject::fgetc()
  • SplFileObject::fpassthru()

Die Methode SplFileObject::hasChildren() hat nun den vorläufigen Rückgabetyp false, vorher war es bool.

Die Methode SplFileObject::getChildren() hat nun den vorläufigen Rückgabetyp null, vorher war es ?RecursiveIterator.

Die Klasse GlobIterator gibt nun ein leeres Array zurück, wenn alle Pfade durch open_basedir eingeschränkt sind. Zuvor gab sie false zurück. Außerdem wird nun eine Warnung ausgegeben, auch wenn nur einige Pfade durch open_basedir eingeschränkt sind.

User Contributed Notes

There are no user contributed notes for this page.


Veraltete Features

PHP-Kern

Verwendung dynamischer Eigenschaften

Das Erstellen dynamischer Eigenschaften ist veraltet, es sei denn, die Klasse erlaubt dies mit dem Attribut #[\AllowDynamicProperties]. stdClass erlaubt dynamische Eigenschaften. Die Verwendung der magischen Methoden __get()/__set() ist von dieser Änderung nicht betroffen. Die Warnung, dass dynamische Eigenschaften veraltet sind, kann wie folgt beseitigt werden:

  • Deklarieren der Eigenschaft (empfohlen).
  • Hinzufügen des Attributs #[\AllowDynamicProperties] zur Klasse (welches auch für alle untergeordneten Klassen gilt).
  • Die Verwendung einer WeakMap, wenn zusätzliche Daten mit einem Objekt verbunden werden müssen, das einem nicht gehört.

Relative Callables

Callables, die nicht von der Syntax $callable() akzeptiert werden (aber von call_user_func()), sind veraltet. Im Besonderen:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
Dies hat keine Auswirkungen auf normale Methoden-Callables wie "A::method" oder ["A", "method"].

Interpolation im Stil von "${var}" und "${expr}"

Die Zeichenketten-Interpolation im Stil von "${var}" und "${expr}" ist veraltet. Stattdessen sollten "$var"/"{$var}" und "{${expr}}" verwendet werden.

MBString

Die Verwendung der "Textkodierungen" QPrint, Base64, Uuencode und HTML-ENTITIES ist bei allen MBString-Funktionen veraltet. Im Gegensatz zu allen anderen Textkodierungen, die von MBString unterstützt werden, kodieren diese keine Sequenz von Unicode-Codepoints, sondern eine Sequenz von rohen Bytes. Es ist daher nicht klar, was die korrekten Rückgabewerte für die meisten MBString-Funktionen sein sollten, wenn eine dieser Nicht-Kodierungen angegeben wird. Außerdem hat PHP separate, eingebaute Implementierungen für alle diese Funktionen; zum Beispiel können UU-kodierte Daten mit convert_uuencode()/convert_uudecode() verarbeitet werden.

Standard-PHP-Bibliothek (SPL)

Die interne Methode SplFileInfo::_bad_state_ex() ist veraltet.

Standard

Die Funktionen utf8_encode() und utf8_decode() sind veraltet.

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


Sonstige Änderungen

PHP-Kern

Der Typ iterable ist nun ein eingebauter Compile-Time-Alias für array|Traversable. Fehlermeldungen, die sich auf iterable beziehen, werden daher nun array|Traversable verwenden. Die Type-Reflection wird für einzelne iterable (und ?iterable) beibehalten, um einen ReflectionNamedType mit dem Namen iterable zu erzeugen, jedoch wird die Bezeichnung iterable in Union-Typen (zusammengefassten Typen) in array|Traversable umgewandelt.

Das Datumsformat gesendeter Cookies ist nun 'D, d M Y H:i:s \G\M\T'; vorher war es 'D, d-M-Y H:i:s T'.

Änderungen in SAPI-Modulen

CLI

Die Streams von STDOUT, STDERR und STDIN werden nicht mehr geschlossen, wenn eine Ressource zerstört wird, was meistens der Fall ist, wenn die CLI beendet wird. Es ist jedoch immer noch möglich, diese Streams mit der Funktion fclose() und ähnlichen explizit zu schließen.

Geänderte Funktionen

PHP-Kern

Die Funktionen strcmp(),
strcasecmp(), strncmp(),
strncasecmp() und substr_compare(),
die den binärsicheren Vergleich von Zeichenketten verwenden, geben nun
-1, 0 und 1 zurück.

DBA

Die Funktionen dba_open() und dba_popen() verlangen nun zwingend die folgende Signatur:

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

Bei der Funktion dba_fetch() steht der optionale Parameter skip nun am Ende und folgt damit der Semantik von PHPs benutzerdefinierten Funktionen. Die Signatur lautet nun:

dba_fetch(string|array $key, resource $handle, int $skip): string|false
Die überladene Signatur:
dba_fetch(string|array $key, int $skip, resource $handle): string|false
wird weiterhin akzeptiert, aber es wird empfohlen, die neue Standardvariante zu verwenden.

Random

Die Funktionen random_bytes() und random_int() lösen bei CSPRNG-Fehlern nun eine \Random\RandomException aus. Zuvor wurde stattdessen eine einfache \Exception ausgelöst.

Standard-PHP-Bibliothek (SPL)

Bei den Funktionen iterator_to_array() und iterator_count() wurde der Parameter iterator von Iterator auf iterable erweitert, wodurch Arrays übergeben werden können.

Sonstige Änderungen bei Erweiterungen

Date

Die Eigenschaften von DatePeriod werden nun korrekt deklariert.

Intl

Die Instanzen von IntlBreakIterator, IntlRuleBasedBreakIterator, IntlCodePointBreakIterator, IntlPartsIterator, IntlCalendar, Collator, IntlIterator, UConverter, IntlDateFormatter, IntlDatePatternGenerator, MessageFormatter, ResourceBundle, Spoofchecker, IntlTimeZone, und Transliterator sind nicht mehr serialisierbar. Zuvor konnten sie zwar serialisiert werden, aber wenn sie deserialisiert wurden, erzeugten sie unbrauchbare Objekte oder die Deserialisierung schlug fehl.

MySQLi

Die Unterstützung für libmysql wurde entfernt und es ist nicht mehr möglich, mysqli mit libmysql zu kompilieren. Die Erweiterung mysqli kann von nun an nur noch mit mysqlnd kompiliert werden. Alle libmysql-Features, die in mysqlnd nicht verfügbar sind, wurden entfernt:

  • Die Eigenschaft reconnect von mysqli_driver
  • Die INI-Direktive mysqli.reconnect
  • Die Konstante MYSQLI_IS_MARIADB ist veraltet

OCI8

Die benötigte Mindestversion der Oracle-Client-Bibliothek ist nun 11.2.

PCRE

NUL-Zeichen (\0) in Suchmustern werden nun unterstützt.

Session

Der Versuch, die INI-Direktive session.cookie_samesite zu ändern, während die Session aktiv ist oder nachdem bereits eine Ausgabe gesendet wurde, schlägt nun fehl und gibt eine Warnung aus. Damit wird das Verhalten an alle anderen INI-Einstellungen für Sessions angeglichen.

SQLite3

sqlite3.defensive ist nun INI_USER.

Standard

Die Funktion getimagesize() meldet nun die tatsächlichen Abmessungen, Bits und Kanäle von AVIF-Bildern; zuvor wurden die Abmessungen als 0x0 zurückgegeben, und Bits und Kanäle wurden überhaupt nicht zurückgegeben.

Tidy

Die Eigenschaften der Klasse tidy sind nun korrekt deklariert; die der Klasse tidyNode sind nun korrekt als schreibgeschützt deklariert.

Zip

Die Erweiterung Zip wurde auf Version 1.20.0 aktualisiert, wodurch die folgenden Methoden hinzugefügt wurden:

  • ZipArchive::clearError()
  • ZipArchive::getStreamName()
  • ZipArchive::getStreamIndex()

Änderungen bei der Handhabung von INI-Dateien

Die INI-Direktiven für Integerwerte wurden um die Möglichkeit erweitert, binäre (0b/0B) und oktale (0o/0O) Präfixe anzugeben. INI-Direktiven, die mit einer Null (0) beginnen, werden weiterhin als oktaler Integer interpretiert.

Wenn bestimmte schlecht formatierte Werte verarbeitet werden, wird nun eine Warnung ausgegeben, während dies zuvor stillschweigend ignoriert wurde. Aus Gründen der Abwärtskompatibilität werden diese Werte weiterhin so interpretiert wie bisher. Dies betrifft die folgenden Einstellungen:

  • bcmath.scale
  • com.code_page
  • default_socket_timeout
  • fiber.stack_size
  • hard_timeout
  • intl.error_level
  • ldap.max_links
  • max_input_nesting_level
  • max_input_vars
  • mbstring.regex_retry_limit
  • mbstring.regex_stack_limit
  • mysqli.allow_local_infile
  • mysqli.allow_persistent
  • mysqli.default_port
  • mysqli.max_links
  • mysqli.max_persistent
  • mysqli.rollback_on_cached_plink
  • mysqlnd.log_mask
  • mysqlnd.mempool_default_size
  • mysqlnd.net_read_buffer_size
  • mysqlnd.net_read_timeout
  • oci8.default_prefetch
  • oci8.max_persistent
  • oci8.persistent_timeout
  • oci8.ping_interval
  • oci8.prefetch_lob_size
  • oci8.privileged_connect
  • oci8.statement_cache_size
  • odbc.allow_persistent
  • odbc.check_persistent
  • odbc.max_persistent
  • odbc.max_links
  • odbc.defaultbinmode
  • odbc.default_cursortype
  • odbc.defaultlrl
  • opcache.consistency_checks
  • opcache.file_update_protection
  • opcache.force_restart_timeout
  • opcache.interned_strings_buffer
  • opcache.jit_bisect_limit
  • opcache.jit_blacklist_root_trace
  • opcache.jit_blacklist_side_trace
  • opcache.jit_debug
  • opcache.jit_hot_func
  • opcache.jit_hot_loop
  • opcache.jit_hot_return
  • opcache.jit_hot_side_exit
  • opcache.jit_max_exit_counters
  • opcache.jit_max_loop_unrolls
  • opcache.jit_max_polymorphic_calls
  • opcache.jit_max_recursive_calls
  • opcache.jit_max_recursive_returns
  • opcache.jit_max_root_traces
  • opcache.jit_max_side_traces
  • opcache.log_verbosity_level
  • opcache.max_file_size
  • opcache.opt_debug_level
  • opcache.optimization_level
  • opcache.revalidate_freq
  • output_buffering
  • pcre.backtrack_limit
  • pcre.recursion_limit
  • pgsql.max_links
  • pgsql.max_persistent
  • post_max_size
  • realpath_cache_size
  • realpath_cache_ttl
  • session.cache_expire
  • session.cookie_lifetime
  • session.gc_divisor
  • session.gc_maxlifetime
  • session.gc_probability
  • soap.wsdl_cache_limit
  • soap.wsdl_cache_ttl
  • unserialize_max_depth
  • upload_max_filesize
  • user_ini.cache_ttl
  • xmlrpc_error_number
  • zend.assertions
  • zlib.output_compression_level

User Contributed Notes

There are no user contributed notes for this page.


Windows-Unterstützung

PHP-Kern

Windows-spezifische Fehlermeldungen werden nicht mehr in der lokalen Sprache angezeigt, sondern immer auf Englisch, um besser mit den PHP Fehlermeldungen übereinzustimmen.

Eine vorläufige und sehr experimentelle Unterstützung für die Kompilierung auf ARM64 wurde hinzugefügt.

OCI8

Die Konfigurationsoption --with-oci8 wurde entfernt, weil die Kompilierung gegen Oracle Client 10g ohnehin nicht mehr unterstützt wird. Die Konfigurationsoptionen --with-oci8-11g, --with-oci8-12c und --with-oci8-19 werden weiterhin unterstützt.

Zip

Die Erweiterung Zip wurde auf Version 1.21.0 aktualisiert und wird nun standardmäßig als Shared Library (DLL) erstellt.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 8.0.x auf PHP 8.1.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Klassen und Interfaces
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Sonstige Änderungen

Diese neue Minor-Version bringt eine Reihe von neuen Features und ein paar wenige Inkompatibilitäten, die vor einem Wechsel der PHP-Version in Produktivumgebungen getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

PHP-Kern

Präfix für oktale Integer-Literale

Bei oktalen Integern ist es nun möglich, explizit 0o oder 0O als Präfix für numerische Literale anzugeben. Dies entspricht der Notation für binäre und hexadezimale Integer-Literale.

<?php
014; // Oktales Literal ohne Präfix
0o14; // Oktales Literal mit Präfix
?>

Entpacken von Arrays mit String-Schlüsseln

Die Unterstützung für das Entpacken von Arrays mit String-Schlüsseln wurde hinzugefügt.

<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>

Benannter Parameter nach dem Entpacken von Parametern

Es ist nun möglich, benannte Parameter nach einem entpackten Parameter anzugeben. z. B. foo(...$args, named: $arg).

Vollständiger Pfad beim Hochladen von Dateien

Datei-Uploads bieten nun einen zusätzlichen full_path-Schlüssel, der den vollständigen Pfad (und nicht nur den Basisnamen) der hochgeladenen Datei enthält. Dies ist für die Verwendung in Verbindung mit dem HTML-Attribut "webkitdirectory" gedacht.

Aufzählungen

Die Unterstützung für Aufzählungen wurde hinzugefügt.

Fibers

Die Unterstützung für Fibers wurde hinzugefügt.

Callback-Funktionen als Objekte erster Klasse

Closures für Callback-Funktionen können nun mit der Syntax myFunc(...) erstellt werden, die identisch ist zu Closure::fromCallable('myFunc').

Hinweis: Das ... ist keine Auslassung, sondern Teil der Syntax.

Schnittmengentypen (Intersection-Typen)

Die Unterstützung für Schnittmengentypen wurde hinzugefügt.

Achtung

Schnittmengentypen können nicht zusammen mit zusammengefassten Typen (Union-Typen) verwendet werden.

Never-Typ

Der neue Rückgabetyp never wurde hinzugefügt. Dieser zeigt an, dass eine Funktion entweder exit() aufruft, eine Exception auslöst, oder nicht beendet wird.

new in Initialisierungen

Es ist nun möglich, new ClassName()-Ausdrücke als Standardwert für die Initialisierung von Parametern, statischen Variablen und globalen Konstanten und als Eigenschafts-Parameter zu verwenden. Objekte können nun ebenfalls an define() übergeben werden.

Schreibgeschützte Eigenschaften

Die Unterstützung für readonly wurde hinzugefügt.

Finale Klassenkonstanten

Die Unterstützung für den Modifikator final für Klassenkonstanten wurde hinzugefügt. Außerdem werden Schnittstellenkonstanten standardmäßig überschreibbar.

CURL

Die Option CURLOPT_DOH_URL wurde hinzugefügt.

Zusätzliche Optionen für Blob-Zertifikate, falls 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

Die Klasse CURLStringFile wurde hinzugefügt. Sie kann dazu verwendet werden, statt einer Datei eine Datei aus einem String zu senden:

<?php
$datei = new CURLStringFile($daten, 'dateiname.txt', 'text/plain');
curl_setopt($curl, CURLOPT_POSTFIELDS, ['datei' => $datei]);
?>

FPM

Ein Openmetrics-Statusformat wurdet hinzugefügt. Es kann von Prometheus verwendet werden, um FPM-Metriken abzurufen.

Für den dynamischen Prozessmanager wurde eine neue Pool-Option namens pm.max_spawn_rate hinzugefügt. Sie ermöglicht ein schnelleres Starten einer Anzahl von Kindprozessen, wenn dynamisches PM ausgewählt ist. Der Standardwert ist 32, was der vorherige fest kodierte Wert war.

GD

Wenn libgd mit Avif-Unterstützung gebaut wurde, steht die Unterstützung von Avif nun über die Funktionen imagecreatefromavif() und imageavif() zur Verfügung.

Hash

Die Funktionen hash(), hash_file() und hash_init() unterstützen nun zusätzlich den optionalen Parameter options, der zur Übergabe von Algorithmus-spezifischen Daten verwendet werden kann.

MurmurHash3

Die Unterstützung für MurmurHash3 mit der Unterstützung für Streaming wurde hinzugefügt. Die folgenden Varianten sind implementiert:

  • murmur3a, 32-Bit-Hash
  • murmur3c, 128-Bit-Hash für x86
  • murmur3f, 128-Bit-Hash für x64

Der anfängliche Hash-Status kann durch den Schlüssel seed im Array options übergeben werden, zum Beispiel:

<?php
$h = hash("murmur3f", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Ein gültiger Seed-Wert liegt im Bereich von 0 bis zum plattformdefinierten UINT_MAX, normalerweise 4294967295.

xxHash

Die Unterstützung für xxHash wurde hinzugefügt. Die folgenden Varianten sind implementiert:

  • xxh32, 32-Bit-Hash
  • xxh64, 64-Bit-Hash
  • xxh3, 64-Bit-Hash
  • xxh128, 128-Bit-Hash

Der anfängliche Hash-Status kann durch den Schlüssel seed im Array options übergeben werden, zum Beispiel:

<?php
$h = hash("xxh3", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Die Verwendung eines geheimen Parameters wird durch Übergeben des Schlüssels secret im Array options ebenfalls unterstützt:
<?php
$h = hash("xxh3", $data, options: ["secret" => "das Geheimnis muss hier mindestens 136 Bytes lang sein"]);
echo $h, "\n";
?>
Die Qualität des benutzerdefinierten geheimen Parameters ist entscheidend für die Qualität des resultierenden Hashes. Es wird dringend empfohlen, für den geheimen Parameter die bestmögliche Entropie zu verwenden.

MySQLi

Neue INI-Directive mysqli.local_infile_directory

Die INI-Direktive mysqli.local_infile_directory wurde hinzugefügt. Sie kann verwendet werden, um ein Verzeichnis anzugeben, aus dem aus dem Dateien geladen werden dürfen. Sie ist nur dann relevant, wenn mysqli.allow_local_infile nicht aktiviert ist, da in diesem Fall alle Verzeichnisse erlaubt sind.

Parameter in execute binden

Es ist nun möglich, Parameter zu binden, indem sie als Array an mysqli_stmt::execute() übergeben werden. Alle Werte werden als Zeichenketten gebunden. Nur Listen-Arrays sind erlaubt. Diese neue Funktion ist nicht verfügbar wenn MySQLi mit libmysqlclient kompiliert wurde.

<?php
$stmt = $mysqli->prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>

Neue Methode mysqli_result::fetch_column()

Die Methode mysqli_result::fetch_column() wurde hinzugefügt, um das Abrufen eines einzelnen skalaren Werts aus der Ergebnismenge zu ermöglichen. Die neue Methode akzeptiert den optionalen 0-basierten Parameter column vom Typ Integer, der angibt, aus welcher Spalte abgerufen werden soll.

<?php
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>

PDO

Die Eigenschaft PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY wurde hinzugefügt. Damit kann ein Verzeichnis angegeben werden, aus dem Dateien geladen werden dürfen. Sie ist nur dann relevant, wenn PDO::MYSQL_ATTR_LOCAL_INFILE nicht aktiviert ist, da in diesem Fall alle Verzeichnisse erlaubt sind.

PDO_SQLite

Die DSN-Syntax "file:" von SQLite wird nun unterstützt, was die Angabe zusätzlicher Flags ermöglicht. Dieses Feature ist nicht verfügbar, wenn open_basedir gesetzt ist.

<?php
new PDO('sqlite:file:path/to/sqlite.db?mode=ro')
?>

POSIX

POSIX_RLIMIT_KQUEUES und POSIX_RLIMIT_NPTS wurden hinzugefügt. Diese rlimits sind nur unter FreeBSD verfügbar.

Standard

Die Funktion fputcsv() akzeptiert nun den neuen Parameter eol, mit dem eine eigene Sequenz für das Zeilenende definiert werden kann. Die Vorgabe bleibt dieselbe wie bisher: "\n".

SPL

Die Methode SplFileObject::fputcsv() akzeptiert nun den neuen Parameter eol, mit dem eine eigene Sequenz für das Zeilenende definiert werden kann. Die Vorgabe bleibt dieselbe wie bisher: "\n".

User Contributed Notes

There are no user contributed notes for this page.


Neue Klassen und Interfaces

cURL

  • CURLStringFile

Intl

  • IntlDatePatternGenerator

Reflection

  • ReflectionFiber

User Contributed Notes

There are no user contributed notes for this page.


Neue Funktionen

PHP-Kern

  • array_is_list()

GD

  • imagecreatefromavif()
  • imageavif()

MySQLi

  • mysqli_result::fetch_column()
  • mysqli_fetch_column()

Prozesskontrolle

  • pcntl_rfork()

Reflection

  • ReflectionFunctionAbstract::getClosureUsedVariables()

Standard

  • fsync()
  • fdatasync()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20()
  • sodium_crypto_stream_xchacha20_keygen()
  • sodium_crypto_stream_xchacha20_xor()

Ristretto255

Die Ristretto255-Funktionen sind seit libsodium 1.0.18 verfügbar.

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


Neue globale Konstanten

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

    Diese Konstante wurde in Übereinstimmung mit einer Upstream-Änderung in MySQL als Ersatz für MYSQLI_REFRESH_SLAVE hinzugefügt. Die alte Konstante ist aus Gründen der Abwärtskompatibilität weiterhin verfügbar, kann aber in Zukunft veraltet sein/entfernt werden.

PCNTL

  • PRIO_DARWIN_BG
  • PRIO_DARWIN_THREAD

POSIX

  • POSIX_RLIMIT_KQUEUES
  • POSIX_RLIMIT_NPTS

Sockets

Die folgenden Socket-Optionen sind nun definiert, wenn sie unterstützt werden:

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


Nicht abwärtskompatible Änderungen

PHP Core

Zugriffsbeschränkungen für $GLOBALS

Der Zugriff auf das Array $GLOBALS unterliegt nun einer einer Reihe von Einschränkungen. Der Lese- und Schreibzugriff auf einzelne Array-Elemente wie $GLOBALS['var'] funktioniert weiterhin wie bisher. Der nur lesende Zugriff auf das Gesamt-Array $GLOBALS wird ebenfalls wird weiterhin unterstützt. Allerdings wird der Schreibzugriff auf das Gesamt-Array $GLOBALS nicht mehr unterstützt. Zum Beispiel wird array_pop($GLOBALS) zu einem Fehler führen.

Verwendung von static-Variablen in geerbten Methoden

Wenn eine Methode, die statische Variablen verwendet, geerbt (aber nicht überschrieben) wird, teilt die geerbte Methode nun die statischen Variablen mit der Methode der Elternklasse.

<?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), vorher int(1)
var_dump(B::counter()); // int(4), vorher int(2)
?>
Das bedeutet, dass sich statische Variablen in Methoden nun genauso verhalten wie statische Eigenschaften.

Angabe optionaler Parameter vor den erforderlichen

Ein optionaler Parameter, der vor den erforderlichen Parametern angegeben wird, wird nun immer als erforderlich angesehen. Dies ist auch der Fall, wenn eine Funktion mit benannten Parametern aufgerufen wird. Seit PHP 8.0.0, aber vor PHP 8.1.0, löst das untenstehende Beispiel einen Hinweis darauf aus, dass die Definition veraltet ist, läuft aber beim Aufruf trotzdem fehlerfrei. Ab PHP 8.1.0 wird ein Fehler der Klasse ArgumentCountError ausgelöst, so wie es auch bei einem Aufruf mit positionsbezogenen Parametern der Fall wäre.

<?php
function makeyogurt($container = "bowl", $flavour)
{
return "Making a $container of $flavour yogurt.\n";
}
try
{
echo makeyogurt(flavour: "raspberry");
}
catch (Error $e)
{
echo get_class($e), ' - ', $e->getMessage(), "\n";
}
?>

Das oben gezeigte Beispiel erzeugt mit PHP 8.0 folgende Ausgabe:

Deprecated: Required parameter $flavour follows optional parameter $container
 in example.php on line 3
Making a bowl of raspberry yogurt.

Das oben gezeigte Beispiel erzeugt mit PHP 8.1 folgende Ausgabe:

Deprecated: Optional parameter $container declared before required parameter
 $flavour is implicitly treated as a required parameter in example.php on line 3
ArgumentCountError - makeyogurt(): Argument #1 ($container) not passed

Es ist zu beachten, dass ein Standardwert von null vor erforderlichen Parametern verwendet werden kann, um einen nullbaren Typ anzugeben, aber der Parameter wird trotzdem benötigt.

Kompatibilität des Rückgabetyps mit internen Klassen

Die meisten nicht-finalen internen Methoden erfordern nun, dass überschreibende Methoden einen kompatiblen Rückgabetyp deklarieren, andernfalls wird bei der Vererbungsüberprüfung ein Hinweis darauf ausgegeben, dass die Funktionsweise veraltet ist. Falls der Rückgabetyp aufgrund von Kompatibilitätsproblemen zwischen PHP-Versionen für eine überschreibende Methode nicht deklariert werden kann, kann das Attribut ReturnTypeWillChange hinzugefügt werden, um den Veraltet-Hinweis zu unterdrücken.

Neue Schlüsselwörter

readonly ist nun ein Schlüsselwort. Es kann jedoch weiterhin als Name einer Funktion verwendet werden.

never ist nun ein reserviertes Wort, sodass es nicht verwendet werden kann, um eine Klasse, eine Schnittstelle oder einen Trait zu benennen, und es darf auch nicht in Namespaces verwendet werden.

Umstellung von Ressourcen auf Objekte

Mehrere Ressourcen wurden zu Objekten migriert. Rückgabewertprüfungen mit is_resource() sollten durch Prüfungen auf false ersetzt werden.

  • Die FileInfo-Funktionen akzeptieren nun finfo-Objekte anstelle von fileinfo-Ressourcen und geben diese auch zurück.

  • Die FTP-Funktionen akzeptieren nun FTP\Connection-Objekte anstelle von ftp-Ressourcen und geben diese auch zurück.

  • Die IMAP-Funktionen akzeptieren nun IMAP\Connection-Objekte anstelle von imap-Ressourcen und geben diese auch zurück.

  • Die LDAP-Funktionen akzeptieren nun LDAP\Connection-Objekte anstelle von ldap link-Ressourcen und geben diese auch zurück.

  • Die LDAP-Funktionen akzeptieren nun LDAP\Result-Objekte anstelle von ldap result-Ressourcen und geben diese auch zurück.

  • Die LDAP-Funktionen akzeptieren nun LDAP\ResultEntry-Objekte anstelle von ldap result entry-Ressourcen und geben diese auch zurück.

  • Die PgSQL-Funktionen akzeptieren nun PgSql\Connection-Objekte anstelle von pgsql link-Ressourcen und geben diese auch zurück.

  • Die PgSQL-Funktionen akzeptieren nun PgSql\Result-Objekte anstelle von pgsql result-Ressourcen und geben diese auch zurück.

  • Die PgSQL-Funktionen akzeptieren nun PgSql\Lob-Objekte anstelle von pgsql large object-Ressourcen und geben diese auch zurück.

  • Die PSpell-Funktionen akzeptieren nun PSpell\Dictionary-Objekte anstelle von pspell-Ressourcen und geben diese auch zurück.

  • Die PSpell-Funktionen akzeptieren nun PSpell\Config-Objekte anstelle von pspell config-Ressourcen und geben diese auch zurück.

MySQLi

mysqli_fetch_fields() und mysqli_fetch_field_direct() geben nun bei der Eigenschaft max_length immer 0 zurück. Dieser Wert kann berechnet werden, indem die Ergebnismenge in einer Schleife durchlaufen und die maximale Länge ermittlt wird. Dies ist der Algorithmus, den PHP zuvor intern verwendet hat.

Die Option MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH hat keine Auswirkung mehr.

Die Option MYSQLI_STORE_RESULT_COPY_DATA hat keine Auswirkung mehr. Die Übergabe eines beliebigen Wertes an den mode-Parameter von mysqli::store_result() hat keine Auswirkung mehr.

mysqli::connect() gibt bei Erfolg nun true anstelle von null zurück.

Der Standard-Fehlerbehandlungsmodus wurde von "silent" auf "exceptions" geändert. Siehe die Seite MySQLi-Berichtsmodus für weitere Details darüber, was das bedeutet, und wie man dieses Attribut explizit setzt. Um das vorherige Verhalten wiederherzustellen, kann folgendes verwendet werden: mysqli_report(MYSQLI_REPORT_OFF);

Klassen, die mysqli_stmt::execute() erweitern, müssen nun den zusätzlichen optionalen Parameter angeben.

MySQLnd

Die INI-Direktive mysqlnd.fetch_data_copy wurde entfernt. Dies sollte zu keinen für den Benutzer sichtbaren Verhaltensänderungen führen.

OpenSSL

Private EC-Schlüssel werden jetzt wie alle anderen Schlüssel im PKCS#8-Format statt im traditionellen Format exportiert.

openssl_pkcs7_encrypt() und openssl_cms_encrypt() verwenden nun standardmäßig AES-128-CBC anstelle von RC2-40. Die RC2-40-Chiffre gilt als unsicher und wird von OpenSSL 3 standardmäßig nicht aktiviert.

PHP-Datenobjekte

PDO::ATTR_STRINGIFY_FETCHES wandelt nun Werte vom Typ Boolean in "0" oder "1" um. Zuvor wurden Booleans nicht stringifiziert.

Wenn PDO::ATTR_STRINGIFY_FETCHES nicht aktiviert ist, Bindet der Aufruf von PDOStatement::bindColumn() mit PDO::PARAM_LOB das Ergebnis eines Streams nun dauerhaft ein. Zuvor war das Ergebnis entweder ein Stream oder eine Zeichenkette, je nach verwendetem Datenbanktreiber und dem Zeitpunkt der Bindung.

MySQL-Treiber

Integer- und Float-Werte in Ergebnismengen werden nun als native PHP-Typen anstelle von Strings zurückgegeben, wenn emulierte vorbereitete Anweisungen verwendet werden. Dies entspricht dem Verhalten von nativen vorbereiteten Anweisungen. Das vorherige Verhalten kann wiederhergestellt werden, indem die Option PDO::ATTR_STRINGIFY_FETCHES aktiviert wird.

SQLite-Treiber

Integer- und Float-Werte in Ergebnismengen werden nun als native PHP-Typen zurückgegeben. Das vorherige Verhalten kann wiederhergestellt werden, indem die Option PDO::ATTR_STRINGIFY_FETCHES aktiviert wird.

Phar

Um der ArrayAccess-Schnittstelle zu entsprechen, geben Phar::offsetUnset() und PharData::offsetUnset() keinen Boolean-Wert mehr zurück.

Standardfunktionen

version_compare() akzeptiert keine undokumentierten Operator-Abkürzungen mehr.

htmlspecialchars(), htmlentities(), htmlspecialchars_decode(), html_entity_decode() und get_html_translation_table() verwenden nun standardmäßig ENT_QUOTES | ENT_SUBSTITUTE anstelle von ENT_COMPAT. Das bedeutet, dass ' zu &#039; umgewandelt wird, während vorher nichts geändert wurde. Darüber hinaus werden fehlerhafte UTF-8-Zeichen durch ein Unicode-Ersatzzeichen ersetzt und nicht mehr durch eine leere Zeichenkette.

debug_zval_dump() gibt nun nicht nur den eigenen Referenzzähler aus, sondern auch den Referenzzähler des Referenz-Wrappers, anstatt dem Wert ein & voranzustellen. Dies ist ein genaueres Modell der Referenzdarstellung seit PHP 7.0.

debug_zval_dump() gibt für festgelegte Zeichenketten und unveränderliche Arrays nun interned aus.

Standard-PHP-Bibliothek (SPL)

SplFixedArray wird nun wie ein Array in JSON kodiert.

User Contributed Notes

There are no user contributed notes for this page.


Veraltete Features

PHP-Kern

Implementierung von Serializable ohne __serialize() und __unserialize()

Sofern keine Unterstützung für PHP-Versionen vor 7.4 erforderlich ist, sollten nur diese beiden magischen Methoden implementiert werden, andernfalls sollten sowohl Schnittstellenmethoden als auch magische Methoden implementiert werden.

Übergabe von null an den Parameter einer eingebauten Funktion, der null nicht erlaubt

Es wird empfohlen, null nicht mehr an skalare Parameter von eingebauten Funktionen zu übergeben. Andernfalls wird nun ein entsprechender Hinweis ausgegeben. Dieses Verhalten wurde eingeführt, um es an die Funktionsweise von benutzerdefinierten Funktionen anzugleichen, bei denen null-validierende Parameter zu diesem Zweck explizit markiert werden müssen.

<?php
var_dump(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
// is deprecated
?>

Implizite Umwandlungen von Float in Integer, die nicht kompatibel sind

Die implizite Umwandlung von Float in Integer, die zu einem Verlust an Genauigkeit führt, ist nun veraltet. Dies betrifft Array-Schlüssel, erzwungene Konvertierungen von Integer-Typen, und Operatoren, die mit Integern arbeiten.

<?php
$a = [];
$a[15.5]; // veraltet, da der Schlüsselwert die 0.5-Komponente verliert
$a[15.0]; // OK, weil 15.0 == 15
?>

Aufruf eines static-Elements bei einem Trait

Der Aufruf einer static-Methode oder der Zugriff auf eine static-Eigenschaft direkt in einem Trait ist veraltet. Auf statische Methoden und Eigenschaften sollte nur in einer Klasse zugegriffen werden, die den Trait verwendet.

Rückgabe eines nicht-Arrays von __sleep()

Die Rückgabe eines Wertes von __sleep(), der kein Array ist, erzeugt nun eine Fehlermeldung.

Rückgabe per Referenz aus einer void-Funktion

<?php
function &test(): void {}
?>
Eine solche Funktion ist widersprüchlich und gibt bereits folgende E_NOTICE-Meldung aus, wenn sie aufgerufen wird: Only variable references should be returned by reference.

Automatische Erstellung (Autovivifikation) von false

Autovivifikation ist der Prozess der automatischen Erstellung eines Arrays, wenn ein Wert hinzugefügt wird. Dies ist bei skalaren Werten verboten, jedoch war false eine Ausnahme. Diese Ausnahme ist nun veraltet.

<?php
$arr = false;
$arr[] = 2; // veraltet
?>

Hinweis:

Die Autovivifikation von null und undefinierten Werten ist weiterhin erlaubt:

<?php
// Von undefiniert
$arr[] = 'ein Wert';
$arr['existiertNicht'][] = 2;
// Von null
$arr = null;
$arr[] = 2;
?>

ctype

Überprüfung von Parametern, die keine Strings sind

Die Übergabe eines Parameters, der kein String ist, ist veraltet. In Zukunft wird der Parameter als String interpretiert und nicht mehr als ASCII-Codepunkt. Je nach beabsichtigtem Verhalten sollte der Parameter entweder nach String umgewandelt werden oder ein expliziter Aufruf von chr() erfolgen. Alle ctype_*()-Funktionen sind betroffen.

Date

Die Funktionen date_sunrise() und
date_sunset() sind zugunsten von
date_sun_info() veraltet.

Die Funktion strptime() ist veraltet. Stattdessen sollte date_parse_from_format() verwendet werden (für Locale-unabhängiges Parsen), oder IntlDateFormatter::parse() (für Locale-abhängiges Parsen).

Die Funktionen strftime() und
gmstrftime() sind veraltet. Stattdessen sollte
date() verwendet werden (für Locale-unabhängige
Formatierung), oder IntlDateFormatter::format() (für
Locale-abhängige Formatierung).

Filter

Die Filter FILTER_SANITIZE_STRING und FILTER_SANITIZE_STRIPPED sind veraltet.

Die INI-Direktive filter.default ist veraltet.

GD

Der Parameter num_points der Funktionen
imagepolygon(),
imageopenpolygon() und
imagefilledpolygon() ist veraltet.

Hash

Die Funktionen mhash(),
mhash_keygen_s2k(), mhash_count(),
mhash_get_block_size() und
mhash_get_hash_name() sind veraltet. Stattdessen sollten
die hash_*()-Funktionen verwendet werden.

IMAP

Die Konstante NIL ist veraltet. Stattdessen sollte 0 verwendet werden.

Intl

Der Aufruf von IntlCalendar::roll() mit einem Boolean-Parameter ist veraltet. Anstelle von true und false sollten 1 bzw. -1 verwendet werden.

Multibyte-String

Der Aufruf von mb_check_encoding() ohne Parameter ist veraltet.

MySQLi

Die Eigenschaft mysqli_driver::$driver_version ist veraltet. Sie war bedeutungslos und überholt; stattdessen sollte PHP_VERSION_ID verwendet werden.

Der Aufruf von mysqli::get_client_info() oder mysqli_get_client_info() mit dem Parameter mysqli ist veraltet. Um die Versionsinformationen der Clientbibliothek zu erhalten, sollte mysqli_get_client_info() ohne Parameter aufgerufen werden.

Die Methode mysqli::init() ist veraltet. Der Aufruf von parent::init() sollte durch parent::__construct() ersetzt werden.

OCI8

Die INI-Direktive oci8.old_oci_close_semantics ist veraltet.

ODBC

odbc_result_all() ist veraltet.

PDO

Der Abrufmodus PDO::FETCH_SERIALIZE ist veraltet.

PgSQL

Den pgsql_*()-Funktionen muss der Verbindungsparameter nun explizit übergeben werden.

SOAP

Die ssl_method-Option von SoapClient::__construct() ist zugunsten der SSL-Streamkontext-Optionen veraltet.

Standard

Der Aufruf von key(), current(), next(), prev(), reset() oder end() bei Objekten ist veraltet. Stattdessen sollte entweder das Objekt vorher mit get_mangled_object_vars() in ein Array umgewandelt werden oder es sollten die Methoden einer Klasse verwendet werden, die Iterator implementiert, z. B. ArrayIterator.

Die INI-Direktive auto_detect_line_endings ist veraltet. Falls nötig, sollten "\r"-Zeilenumbrüche stattdessen manuell bearbeitet werden.

Die Konstanten FILE_BINARY und FILE_TEXT sind veraltet. Sie hatten nie eine Auswirkung.

User Contributed Notes

There are no user contributed notes for this page.


Sonstige Änderungen

Änderungen in SAPI-Modulen

CLI

Die Verwendung der Option -a ohne die Erweiterung readline führt nun zu einem Fehler. Zuvor hatte -a ohne readline, abgesehen von der zusätzliche Meldung "Interactive mode enabled", das gleiche Verhalten wie der Aufruf von php ohne Parameter. Dieser Modus war nicht interaktiv.

PHPDBG

Die Fähigkeit, remote zu debuggen, wurde von phpdbg entfernt.

Geänderte Funktionen

PHP-Kern

Die Reihenfolge der Eigenschaften, die in foreach, var_dump(), serialize(), Objektvergleichen etc. verwendet werden, wurde geändert. Die Eigenschaften sind jetzt so geordnet, wie sie deklariert und vererbt wurden. Die Eigenschaften, die in einer Basisklasse deklariert sind, stehen vor den Kind-Eigenschaften.

Diese Reihenfolge entspricht dem internen Layout der Eigenschaften in der zend_object-Struktur und reproduziert die Reihenfolge in default_properties_table[] und properties_info_table[]. Die alte Reihenfolge war nicht dokumentiert und wurde durch Implementierungsdetails der Klassenvererbung verursacht.

Filter

Das Flag FILTER_FLAG_ALLOW_OCTAL des Filters FILTER_VALIDATE_INT akzeptiert nun oktale Zeichenketten mit vorangestelltem Oktalpräfix ("0o"/"0O").

GMP

Alle GMP-Funktionen akzeptieren nun oktale Zeichenketten mit vorangestelltem Oktalpräfix ("0o"/"0O").

PDO ODBC

Die Methode PDO::getAttribute() gibt in Verbindung
mit PDO::ATTR_SERVER_INFO und
PDO::ATTR_SERVER_VERSION nun Werte zurück, anstatt
eine PDOException auszulösen.

Reflection

Die Methoden ReflectionProperty::setAccessible() und ReflectionMethod::setAccessible() haben keine Auswirkung mehr. Bei Eigenschaften und Methoden wird nun immer davon ausgegangen, dass sie über Reflection zugänglich sind.

Standard

syslog() ist nun binärsicher.

Sonstige Änderungen bei Erweiterungen

GD

imagewebp() kann nun durch Übergabe von IMG_WEBP_LOSSLESS als Qualitätsparameter verlustfreie WebP-Kodierungen durchführen.

Diese Konstante ist nur definiert, wenn die verwendete libgd die verlustfreie WebP-Kodierung unterstützt.

MySQLi

Wenn PHP gegen die Bibliothek libmysqlclient gelinkt wird, sind nun die Funktionen mysqli_stmt::next_result() und mysqli::fetch_all() verfügbar.

OpenSSL

  • Die Erweiterung OpenSSL benötigt nun mindestens die OpenSSL-Version 1.0.2.

  • OpenSSL 3.0 wird nun unterstützt. Es ist zu beachten, dass viele Verschlüsselungsmethoden nicht mehr standardmäßig aktiviert sind (es handelt sich um einen Teil des Legacy-Anbieters), und dass die Validierung (z. B. minimale Schlüsselgrößen) jetzt strenger ist.

Phar

  • Für Signaturen wird nun standardmäßig SHA256 verwendet.

  • Die Unterstützung für OpenSSL_SHA256- und OpenSSL_SHA512-Signaturen wurde hinzugefügt.

SNMP

  • Für das Sicherheitsprotokoll wurde die Unterstützung für SHA256 und SHA512 hinzugefügt.

Standard

--with-password-argon2 verwendet nun pkg-config, um libargon2 zu erkennen. Aus diesem Grund sollte ein alternativer Speicherort für libargon2 nun mittels PKG_CONFIG_PATH angegeben werden.

Änderungen bei der Handhabung von INI-Dateien

  • Die INI-Direktive log_errors_max_len wurde entfernt. Sie hatte seit PHP 8.0.0 keine Wirkung mehr.

  • Ein vorangestelltes Dollarzeichen in einer Zeichenkette mit Anführungszeichen kann nun maskiert werden: "\${" wird nun als Zeichenkette mit dem Inhalt ${ interpretiert.

  • Backslashes in Zeichenketten mit doppelten Anführungszeichen werden nun konsequenter als Maskierungs-Zeichen behandelt. Zuvor galt "foo\" gefolgt von etwas anderem als einem Zeilenumbruch als unvollständige Zeichenkette. Jetzt wird sie als Zeichenkette mit dem Inhalt foo\ interpretiert. Als Ausnahme wird jedoch die Zeichenkette "foo\" gefolgt von einem Zeilenumbruch weiterhin als gültige Zeichenkette mit Inhalt foo\ behandelt und nicht als unvollständige Zeichenkette. Diese Ausnahme existiert, um die einfache Verwendungen von Windows-Dateipfaden, z. B. "C:\foo\", zu unterstützen.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 7.4.x auf PHP 8.0.x

Inhaltsverzeichnis

  • Neue Features
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Sonstige Änderungen

Diese neue Hauptversion bringt eine Reihe von neuen Features und ein paar Inkompatibilitäten, die vor einem Wechsel der PHP-Version in Produktivumgebungen getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 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.


Neue Features

PHP-Kern

Benannte Parameter

Die Unterstützung für benannte Parameter wurde hinzugefügt.

Attribute

Die Unterstützung für Attribute wurde hinzugefügt.

Beförderung von Konstruktoreigenschaften

Die Unterstützung für die Beförderung von Konstruktoreigenschaften (Deklaration von Eigenschaften in der Konstruktorsignatur) wurde hinzugefügt.

Zusammengefasste Typen (Union-Typen)

Die Unterstützung für zusammengefasste Typen wurde hinzugefügt.

Ausdruck match

Die Unterstützung für den Ausdruck match wurde hinzugefügt.

Nullsafe-Operator

Die Unterstützung für den nullsafe-Operator (?->) wurde hinzugefügt.

Andere neue Features

  • Die Klasse WeakMap wurde hinzugefügt.

  • Die Klasse ValueError wurde hinzugefügt.

  • Eine beliebige Anzahl von Funktionsparametern kann nun durch einen variadischen Parameter ersetzt werden, solange die Typen kompatibel sind. Zum Beispiel ist der folgende Code nun erlaubt:

    <?php
    class A {
    public function     method(int $many, string $parameters, $here) {}
    }
    class     B extends A {
    public function     method(...$everything) {}
    }
    ?>

  • static (wie in "late static binding", späte statische Bindung) kann nun als Rückgabetyp verwendet werden:

    <?php
    class Test {
    public function     create(): static {
    return new static();
    }
    }
    ?>

  • Es ist nun möglich, den Klassennamen eines Objekts mit Hilfe von $object::class zu ermitteln. Das Ergebnis ist dasselbe wie bei get_class($object).

  • new und instanceof können nun durch Verwendung von new (Ausdruck)(...$args) und $obj instanceof (Ausdruck) mit beliebigen Ausdrücken verwendet werden.

  • Es wurden einige Verbesserungen an der Einheitlichkeit der Variablensyntax vorgenommen, zum Beispiel ist Folgendes nun erlaubt: Foo::BAR::$baz.

  • Die Schnittstelle Stringable wurde hinzugefügt. Sie wird automatisch implementiert, wenn eine Klasse eine __toString()-Methode definiert.

  • Traits können nun abstrakte private Methoden definieren. Diese Methoden müssen von der Klasse implementiert werden, die den Trait verwendet.

  • throw kann nun als Ausdruck verwendet werden. Das ermöglicht Verwendungen wie:

    <?php
    $fn     = fn() => throw new Exception('Exception in der Pfeilfunktion');
    $user = $session->user ?? throw new Exception('Muss einen Benutzer haben');

  • In Parameterlisten ist nun ein optionales Komma am Ende erlaubt.

    <?php
    function functionWithLongSignature(
    Type1 $parameter1,
    Type2 $parameter2, // <-- Dieses Komma ist nun erlaubt.
    ) {
    }

  • Es ist nun möglich, catch (Exception) zu schreiben, um eine Ausnahme abzufangen, ohne sie in einer Variablen zu speichern.

  • Die Unterstützung für den Typ mixed wurde hinzugefügt.

  • Private Methoden, die in einer übergeordneten Klasse deklariert wurden, erzwingen für die Methoden einer Kindklasse keine Vererbungsregeln mehr (mit Ausnahme von finalen privaten Konstruktoren). Das folgende Beispiel veranschaulicht, welche Einschränkungen aufgehoben wurden:

    <?php
    class ParentClass {
    private function     method1() {}
    private function     method2() {}
    private static function     method3() {}
    // Löst eine Warnung aus, da "final" keine Bedeutung mehr hat:
    private final function method4() {}
    }
    class     ChildClass extends ParentClass {
    // Alles Folgende ist nun erlaubt, auch wenn die Modifikatoren nicht
    // dieselben sind wie bei den privaten Methoden in der Elternklasse.
    public abstract function method1() {}
    public static function     method2() {}
    public function     method3() {}
    public function     method4() {}
    }
    ?>

  • Die Funktion get_resource_id() wurde hinzugefügt. Sie gibt denselben Wert zurück wie (int) $resource und bietet dieselbe Funktionalität mit einer übersichtlicheren API.

  • Die Klasse InternalIterator wurde hinzugefügt.

Datum und Uhrzeit

  • Die Methoden DateTime::createFromInterface() und DateTimeImmutable::createFromInterface() wurden hinzugefügt.

  • Für DateTime wurde die Formatangabe p hinzugefügt, die ähnlich ist wie P, aber für UTC Z anstelle von +00:00 zurückgibt.

DOM

Die Schnittstellen DOMParentNode und DOMChildNode mit neuen Traversal- und Kontroll-APIs wurden hinzugefügt.

Filter

FILTER_VALIDATE_BOOL wurde als Alias für FILTER_VALIDATE_BOOLEAN hinzugefügt. Der neue Name sollte bevorzugt werden, weil er den kanonischen Typnamen verwendet.

Enchant

Die Funktionen enchant_dict_add(), enchant_dict_is_added() und die Konstante LIBENCHANT_VERSION wurden hinzugefügt.

FPM

Die neue Option pm.status_listen wurde hinzugefügt. Sie ermöglicht es, den Status von einem anderen Endpunkt zu erhalten (z. B. Port oder UDS-Datei). Dies ist nützlich, um den Status zu erhalten, wenn alle Kindprozesse mit der Bearbeitung lang laufender Anfragen beschäftigt sind.

Hash

HashContext-Objekte können nun serialisiert werden.

Funktionen für die Internationalisierung

Die Konstanten IntlDateFormatter::RELATIVE_FULL,
IntlDateFormatter::RELATIVE_LONG,
IntlDateFormatter::RELATIVE_MEDIUM und
IntlDateFormatter::RELATIVE_SHORT wurden hinzugefügt.

LDAP

Die Funktion ldap_count_references() wurde hinzugefügt; sie gibt die Anzahl der Referenzmeldungen in einem Suchergebnis zurück.

OPcache

Wenn die ini-Einstellung opcache.record_warnings aktiviert ist, zeichnet OPcache die Warnungen auf, die bei der Kompilierung auftreten, und gibt sie beim nächsten Include wieder, auch wenn sie aus dem Cache geliefert werden.

OpenSSL

Die Unterstützung für die Cryptographic Message Syntax (CMS) (» RFC 5652), die aus Funktionen zum Verschlüsseln, Entschlüsseln, Signieren, Überprüfen und Lesen besteht, wurde hinzugefügt. Die API ist der API für PKCS-#7-Funktionen ähnlich und enthält darüber hinaus folgende neue Verschlüsselungskonstanten: OPENSSL_ENCODING_DER, OPENSSL_ENCODING_SMIME und OPENSSL_ENCODING_PEM:

  • openssl_cms_encrypt() verschlüsselt die Nachricht in der Datei mit den Zertifikaten und gibt das Ergebnis in der angegebenen Datei aus.
  • openssl_cms_decrypt() entschlüsselt die S/MIME-Nachricht in der Datei und gibt das Ergebnis in der angegebenen Datei aus.
  • openssl_cms_read() exportiert die CMS-Datei in ein Array von PEM-Zertifikaten.
  • openssl_cms_sign() signiert die MIME-Nachricht in der Datei mit einem Zertifikat und einem Schlüssel und gibt das Ergebnis in der angegebenen Datei aus.
  • openssl_cms_verify() verifiziert, dass der Datenblock intakt ist, der Unterzeichner der ist, für den er sich ausgibt, und gibt die Zertifikate der Unterzeichner zurück.

Reguläre Ausdrücke (Perl-kompatibel)

Die Funktion preg_last_error_msg() wurde hinzugefügt. Sie gibt eine menschenlesbare Meldung für den letzten PCRE-Fehler zurück und ergänzt die Funktion preg_last_error(), die einen Integer-Enum-Wert zurückgibt.

Reflection

  • Die folgenden Methoden können nun Informationen über die Standardwerte der Parameter interner Funktionen zurückgeben:

    • ReflectionParameter::isDefaultValueAvailable()
    • ReflectionParameter::getDefaultValue()
    • ReflectionParameter::isDefaultValueConstant()
    • ReflectionParameter::getDefaultValueConstantName()

SQLite3

Die Methode SQLite3::setAuthorizer() und entsprechende Klassenkonstanten wurden hinzugefügt. Damit ist es möglich, eine benutzerdefinierte Callback-Funktion anzugeben, die verwendet wird, um eine Aktion in der Datenbank zu autorisieren oder nicht.

Standard-Funktionsbibliothek

  • Die Funktionen str_contains(),
str_starts_with() und
str_ends_with() wurden hinzugefügt. Sie prüfen, ob
haystack needle enthält
bzw. damit beginnt oder endet.

  • Die Funktion fdiv() wurde hinzugefügt. Sie führt eine Gleitkomma-Division nach IEEE 754-Semantik durch. Die Division durch Null wird als wohldefiniert betrachtet und gibt einen der Werte Inf, -Inf oder NaN zurück.

  • Die Funktion get_debug_type() wurde hinzugefügt. Sie gibt einen Typ zurück, der für Fehlermeldungen nützlich ist. Anders als gettype() verwendet sie kanonische Typnamen, gibt die Klassennamen von Objekten zurück und nennt bei Ressourcen den Ressourcentyp.

  • Die Funktionen printf() und Freunde unterstützen nun die Formatangaben %h und %H. Diese sind vergleichbar mit %g und %G, verwenden aber immer "." als Dezimaltrennzeichen, anstatt es durch die LC_NUMERIC-Locale zu bestimmen.

  • Die Funktionen printf() und Freunde unterstützen nun die Verwendung von "*" als Breite oder Genauigkeit. In diesem Fall wird die Breite/Genauigkeit als Parameter an printf übergeben. Außerdem ermöglicht dies bei %g, %G, %h und %H die Verwendung der Genauigkeit -1. Zum Beispiel kann der folgende Code verwendet werden, um die standardmäßige Gleitkomma-Formatierung von PHP zu reproduzieren:

    <?php
    printf    ("%.*H", (int) ini_get("precision"), $float);
    printf("%.*H", (int) ini_get("serialize_precision"), $float);
    ?>

  • Die Funktion proc_open() unterstützt nun Pseudo-Terminal (PTY)-Deskriptoren. Das folgende hängt stdin, stdout und stderr an dasselbe PTY an:

    <?php
    $proc     = proc_open($command, [['pty'], ['pty'], ['pty']], $pipes);
    ?>

  • proc_open() unterstützt nun Socket-Paar-Deskriptoren. Das folgende fügt ein bestimmtes Socket-Paar an stdin, stdout und stderr an:

    <?php
    $proc     = proc_open($command, [['socket'], ['socket'], ['socket']], $pipes);
    ?>

    Im Gegensatz zu Pipes gibt es bei Sockets unter Windows keine Probleme mit blockierenden I/Os. Allerdings funktionieren nicht alle Programme korrekt mit stdio-Sockets.

  • Die Sortierfunktionen verwenden nun eine stabile Sortierung. Das bedeutet, dass Elemente, die verglichen und für gleich befunden werden, ihre ursprüngliche Reihenfolge beibehalten.

  • Die Funktionen array_diff(), array_intersect() und ihre Variationen können nun mit einem einzigen Array als Parameter verwendet werden. Das bedeutet, dass Verwendungen wie die folgende nun möglich sind:

    <?php
    // OK, auch wenn $excludes leer ist:
    array_diff($array, ...$excludes);
    // OK, auch wenn $arrays nur ein einziges Array enthält:
    array_intersect(...$arrays);
    ?>

  • Der Parameter flag der Funktion ob_implicit_flush() akzeptiert nun ein bool anstelle eines int.

Tokenizer

Die Klasse PhpToken fügt dem Tokenizer eine objektbasierte Schnittstelle hinzu. Diese Klasse bietet eine einheitlichere und ergonomischere Darstellung ist zudem speichereffizienter und schneller.

Zip

  • Die Erweiterung Zip wurde auf die Version 1.19.1 aktualisiert.

  • Neue Methoden ZipArchive::setMtimeName() und ZipArchive::setMtimeIndex(), um die Änderungszeit eines Eintrags festzulegen.

  • Neue Methode ZipArchive::registerProgressCallback(), um Aktualisierungen beim Schließen eines Archivs bereitzustellen.

  • Neue Methode ZipArchive::registerCancelCallback(), um einen Abbruch während des Schließens eines Archivs zu ermöglichen.

  • Neue Methode ZipArchive::replaceFile(), um den Inhalt eines Eintrags zu ersetzen

  • Neue Methode ZipArchive::isCompressionMethodSupported(), um auf optionale Komprimierungsfunktionen zu prüfen.

  • Neue Methode ZipArchive::isEncryptionMethodSupported(), um auf optionale Verschlüsselungsfunktionen zu prüfen.

  • Die Eigenschaft ZipArchive::lastId wurde hinzugefügt, um den Indexwert des zuletzt eingefügten Eintrags zu erhalten.

  • Mit den Eigenschaften ZipArchive::status und
ZipArchive::statusSys oder der Methode
ZipArchive::getStatusString() können nun Fehler
nach dem Schließen eines Archivs überprüft werden.

  • Die Option 'remove_path' der Methoden ZipArchive::addGlob() und ZipArchive::addPattern() wird nun als beliebiges Zeichenketten-Präfix behandelt (um mit der Option 'add_path' konsistent zu sein), während sie früher als Verzeichnisname behandelt wurde.

  • Optionale Komprimierungs- und Verschlüsselungsfunktionen werden nun in phpinfo aufgelistet.

User Contributed Notes

There are no user contributed notes for this page.


Nicht abwärtskompatible Änderungen

PHP-Kern

Vergleich zwischen Zeichenketten und Zahlen

Einfache (nicht-strikte) Vergleiche zwischen Zahlen und nicht-numerischen Zeichenketten erfolgen nun durch Umwandlung der Zahl in eine Zeichenkette und den Vergleich der Zeichenketten. Vergleiche zwischen Zahlen und numerischen Zeichenketten funktionieren weiterhin wie bisher. Insbesondere bedeutet dies, dass 0 == "keine Zahl" nun als falsch angesehen wird.

Vergleich | Vor der Änderung | Nach der Änderung
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Andere inkompatible Änderungen

  • match ist nun ein reserviertes Schlüsselwort.

  • mixed ist nun ein reserviertes Wort, kann also nicht zur Benennung einer Klasse, Schnittstelle oder eines Traits verwendet werden und darf auch nicht in Namespaces verwendet werden.

  • Assertion-Fehler werden nun standardmäßig ausgelöst. Wenn das alte Verhalten gewünscht wird, kann in den INI-Einstellungen assert.exception=0 gesetzt werden.

  • Methoden mit dem gleichen Namen wie die Klasse werden nicht mehr als Konstruktoren interpretiert. Stattdessen sollte die Methode __construct() verwendet werden.

  • Die Möglichkeit, nicht-statische Methoden statisch aufzurufen, wurde entfernt. Deshalb schlägt is_callable() fehl, wenn eine nicht-statische Methode mit einem Klassennamen geprüft wird (muss mit einer Objektinstanz überprüft werden).

  • Die Typumwandlungen (real) und (unset) wurden entfernt.

  • Die INI-Direktive track_errors wurde entfernt. Das bedeutet, dass php_errormsg nicht mehr verfügbar ist. Stattdessen kann die Funktion error_get_last() verwendet werden.

  • Die Möglichkeit, Konstanten ohne Berücksichtigung der Groß- und Kleinschreibung zu definieren, wurde entfernt. Das dritte Argument von define() kann nicht mehr true sein.

  • Die Möglichkeit, einen Autoloader mit einer __autoload()-Funktion anzugeben, wurde entfernt. Stattdessen sollte spl_autoload_register() verwendet werden.

  • Der Parameter errcontext wird nicht mehr an benutzerdefinierte Fehlerbehandlungen übergeben, die mit der Funktion set_error_handler() gesetzt wurden.

  • Die Funktion create_function() wurde entfernt. Stattdessen können anonyme Funktionen verwendet werden.

  • Die Funktion each() wurde entfernt. Stattdessen sollte foreach oder ArrayIterator verwendet werden.

  • Die Möglichkeit, die Bindung von this an Closures aufzuheben, die mittels Closure::fromCallable() oder ReflectionMethod::getClosure() aus einer Methode erzeugt wurden, wurde entfernt.

  • Die Möglichkeit, die Bindung von this an echte Closures aufzuheben, die this verwenden, wurde ebenfalls entfernt.

  • Die Möglichkeit, die Funktion array_key_exists() mit Objekten zu verwenden, wurde entfernt. Stattdessen können isset() oder property_exists() verwendet werden.

  • Das Verhalten der Funktion array_key_exists() entspricht bezüglich des Typs des Parameters key nun dem Verhalten der Funktion isset() und dem normalen Array-Zugriff. Alle Schlüsseltypen unterliegen nun den üblichen Einschränkungen und Array- und Objektschlüssel lösen einen TypeError aus.

  • Jedes Array, das eine Zahl n als ersten numerischen Schlüssel hat, verwendet n+1 für seinen nächsten impliziten Schlüssel, auch wenn n negativ ist.

  • Die voreingestellte Stufe von error_reporting ist nun E_ALL; zuvor waren E_NOTICE und E_DEPRECATED ausgeschlossen.

  • display_startup_errors ist nun standardmäßig aktiviert.

  • Die Verwendung von parent innerhalb einer Klasse, die keine übergeordnete Klasse hat, führt nun bei der Kompilierung zu einem schweren Fehler.

  • Der Operator @ unterdrückt nun keine schweren Fehler (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR und E_PARSE) mehr. Error-Handler, die erwarten, dass error_reporting 0 ist, wenn @ verwendet wird, sollten so angepasst werden, dass sie stattdessen die Fehler-Maske prüfen:

    <?php
    // Dies ersetzen
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (    error_reporting() == 0) {
    return     false;
    }
    // ...
    }

    // mit Folgendem
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (!(    error_reporting() & $err_no)) {
    return     false;
    }
    // ...
    }
    ?>

    Darüber hinaus sollte in Produktivumgebungen darauf geachtet werden, dass keine Fehlermeldungen angezeigt werden, da dies zu Informationslecks führen kann. Es sollte sichergestellt werden, dass in Verbindung mit der Fehleraufzeichnung display_errors=Off verwendet wird.

  • #[ wird nicht mehr als Beginn eines Kommentars interpretiert, weil diese Syntax nun für Attribute verwendet wird.

  • Vererbungsfehler aufgrund von inkompatiblen Methodensignaturen (Verletzung des Liskovschen Substitutionsprinzip, LSP) führen nun immer zu einem schweren Fehler. Vorher wurde in manchen Fällen eine Warnung erzeugt.

  • Die Rangfolge des Verkettungsoperators hat sich gegenüber Bitverschiebungen sowie Addition und Subtraktion geändert.

    <?php
    echo "Summe: " . $a + $b;
    // wurde früher wie folgt interpretiert:
    echo ("Summe: " . $a) + $b;
    // wird nun interpretiert als:
    echo "Summe: " . ($a + $b);
    ?>

  • Ein Parameter mit einem Standardwert, der bei der Ausführung zu null aufgelöst wird, wird nicht mehr implizit als nullbarer Parameter gekennzeichnet. Stattdessen muss explizit entweder ein nullbarer Typ oder der Standardwert null verwendet werden.

    <?php
    // Dies ersetzen
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // mit
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // oder
    function test(int $arg = null) {}
    ?>

  • Einige Warnungen wurden in Error-Exceptions umgewandelt:

    • Der Versuch, in eine Eigenschaft eines Nicht-Objekts zu schreiben. Zuvor wurde dadurch implizit ein stdClass-Objekt für null, false und leere Zeichenketten erstellt.
    • Der Versuch, ein Element an ein Array anzuhängen, für das bereits der Schlüssel PHP_INT_MAX verwendet wird.
    • Der Versuch, einen ungültigen Typ (Array oder Objekt) als Array-Schlüssel oder Zeichenketten-Offset zu verwenden.
    • Der Versuch, in einen Array-Index eines skalaren Wertes zu schreiben.
    • Der Versuch, ein Nicht-Array/Traversable zu entpacken.
    • Der Versuch, auf unqualifizierte Konstanten zuzugreifen, die nicht definiert sind. Zuvor führten Zugriffe auf unqualifizierte Konstanten zu einer Warnung und wurden als Zeichenketten interpretiert.
    • Wenn die falsche Anzahl von Argumenten an eine interne Funktion übergeben wird, die keinen Parameter mit variabler Länge hat, wird ein ArgumentCountError geworfen.
    • Wenn ungültige zählbare Typen an count() übergeben werden, wird ein TypeError geworfen.

    Einige Hinweise wurden in Warnungen umgewandelt:

    • Der Versuch, eine undefinierte Variable zu lesen.
    • Der Versuch, eine undefinierte Eigenschaft zu lesen.
    • Der Versuch, einen undefinierten Array-Schlüssel zu lesen.
    • Der Versuch, eine Eigenschaft eines Nicht-Objekts zu lesen.
    • Der Versuch, auf einen Array-Index eines Nicht-Arrays zuzugreifen.
    • Der Versuch, ein Array in eine Zeichenkette zu konvertieren.
    • Der Versuch, eine Ressource als Array-Schlüssel zu verwenden.
    • Der Versuch, null, einen Boolean oder einen Float als Zeichenketten-Offset zu verwenden.
    • Der Versuch, einen Zeichenketten-Offset zu lesen, der außerhalb des zulässigen Bereichs liegt.
    • Der Versuch, einem Zeichenketten-Offset eine leere Zeichenkette zuzuweisen.

  • Der Versuch, einem Zeichenketten-Offset mehrere Bytes zuzuweisen, führt nun zu einer Warnung.

  • Unerwartete Zeichen in Quelldateien (z. B. NUL-Bytes außerhalb von Zeichenketten) führen nun statt zu einer Warnung beim Kompilieren zu einer ParseError-Exception.

  • Nicht abgefangene Exceptions durchlaufen nun einen "sauberen Shutdown", was bedeutet, dass nach einer nicht abgefangenen Exception die Destruktoren aufgerufen werden.

  • Der bei der Kompilierung auftretende schwere Fehler "Only variables can be passed by reference" wurde in die Laufzeit verschoben und in die Error-Exception "Argument cannot be passed by reference" umgewandelt.

  • Einige "Only variables should be passed by reference"-Hinweise wurden in die Exception "Argument cannot be passed by reference" umgewandelt.

  • Der für anonyme Klassen erzeugte Name hat sich geändert. Er enthält nun den Namen des ersten Elternteils oder der ersten Schnittstelle:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    Auf den oben gezeigten Namen folgen noch ein NUL-Byte und ein eindeutiges Suffix.

  • Verweise auf nicht-absolute Trait-Methoden in Anpassungen von Trait-Aliasen müssen nun eindeutig sein:

    <?php
    class X {
    use     T1, T2 {
    func as otherFunc;
    }
    function     func() {}
    }
    ?>

    Wenn sowohl T1::func() als auch T2::func() existieren, wurde dieser Code bisher stillschweigend akzeptiert, und es wurde angenommen, dass func sich auf T1::func bezieht. Nun erzeugt er stattdessen einen schweren Fehler und es muss explizit entweder T1::func oder T2::func geschrieben werden.

  • Die Signatur von abstrakten Methoden, die in Traits definiert sind, wird nun anhand der Methode der implementierenden Klasse überprüft:

    <?php
    trait MyTrait {
    abstract private function     neededByTrait(): string;
    }

    class     MyClass {
    use     MyTrait;

    // Fehler, da der Rückgabetyp nicht übereinstimmt.
    private function neededByTrait(): int { return 42; }
    }
    ?>

  • Deaktivierte Funktionen werden nun genauso behandelt wie nicht existierende Funktionen. Wenn eine deaktivierte Funktion aufgerufen wird, wird sie als unbekannt gemeldet, und es ist nun möglich, eine deaktivierte Funktion neu zu definieren.

  • data://-Stream-Wrapper sind nicht mehr beschreibbar, was dem dokumentierten Verhalten entspricht.

  • Die arithmetischen und bitweisen Operatoren +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++ und -- lösen nun ausnahmslos einen TypeError aus, wenn einer der der Operanden ein Array, eine Ressource oder ein nicht überladenes Objekt ist. Die einzige Ausnahme hiervon ist die Array-Zusammenführung Array + Array, die weiterhin unterstützt wird.

  • Die Umwandlung vom Typ Float in den Typ String erfolgt nun immer unabhängig von der Locale.

    <?php
    setlocale    (LC_ALL, "de_DE");
    $f = 3.14;
    echo     $f, "\n";
    // Vorher: 3,14
    // Jetzt: 3.14
    ?>

    Siehe printf(), number_format() und NumberFormatter() für Möglichkeiten, die Formatierung von Zahlen anzupassen.

  • Die Unterstützung für die veraltete Verwendung von geschweiften Klammern für den Offset-Zugriff wurde entfernt.

    <?php
    // Anstelle von:
    $array{0};
    $array{"key"};
    // schreiben Sie:
    $array[0];
    $array["key"];
    ?>

  • Wenn der final-Modifikator auf eine private Methode angewendet wird, wird nun eine Warnung erzeugt, es sei denn, die Methode ist der Konstruktor.

  • Wenn im Konstruktor eines Objekts exit() aufgerufen wird, wird der Destruktor des Objekts nicht mehr aufgerufen. Dies entspricht dem Verhalten, wenn ein Konstruktor eine Exception auslöst.

  • Namen mit Bezug auf einen Namensraum dürfen keine Leerzeichen mehr enthalten: Während Foo\Bar als Namensraum-Name erkannt wird, wird Foo \ Bar nicht erkannt. Umgekehrt sind reservierte Schlüsselwörter nun als Namensraumsegmente erlaubt, was auch die Interpretation des Codes verändern kann: new\x ist nun gleichbedeutend mit constant('new\x'), nicht mit new \x().

  • Verschachtelte ternäre Ausdrücke müssen nun explizit in Klammern gesetzt werden.

  • Die Funktionen debug_backtrace() und Exception::getTrace() referenzieren nun keine Parameter mehr. Es ist nicht mehr möglich, über einen Backtrace die Parameter einer Funktion zu ändern.

  • Die Handhabung numerischer Zeichenketten wurde geändert, damit sie intuitiver und weniger fehleranfällig ist. Nachfolgende Leerzeichen sind nun in numerischen Zeichenketten erlaubt, um mit der Behandlung von führenden Leerzeichen übereinzustimmen. Dies betrifft hauptsächlich:

    • Die Funktion is_numeric()
    • Vergleiche zwischen Zeichenketten
    • Typdeklarationen
    • Inkrement- und Dekrement-Operationen

    Das Konzept einer "vorangestellten numerischen Zeichenkette" wurde größtenteils aufgegeben; die Fälle, in denen dies beibehalten wird, dienen dazu, die Umstellung zu erleichtern. Zeichenketten, die eine E_NOTICE "A non well-formed numeric value encountered" ausgaben, geben nun eine E_WARNING "A non-numeric value encountered" aus, und alle Zeichenketten, die eine E_WARNING "A non-numeric value encountered" ausgaben, lösen nun einen TypeError aus. Dies betrifft vor allem:

    • Arithmetische Operationen
    • Bitweise Operationen

    Diese Änderung von E_WARNING zu TypeError betrifft auch die E_WARNING "Illegal string offset 'string'" für unzulässige Zeichenketten-Offsets. Das Verhalten von expliziten Umwandlungen von Zeichenketten in int/float hat sich nicht geändert.

  • Magische Methoden werden nun auf ihre Parameter und Rückgabetypen geprüft, falls sie diese deklariert haben. Die Signaturen sollten der folgenden Liste entsprechen:

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

  • Array-Schlüssel, die an die Funktion call_user_func_array() übergeben werden, werden nun als Namen der Parameter interpretiert. In früheren Versionen wurden sie stillschweigend ignoriert.

  • Die Deklaration einer Funktion namens assert() innerhalb eines Namensraums ist nicht mehr erlaubt und erzeugt einen E_COMPILE_ERROR. Die Funktion assert() unterliegt einer speziellen Verarbeitung durch die Engine, was zu einem inkonsistenten Verhalten führen kann, wenn eine Funktion mit demselben Namen innerhalb eines Namensraums definiert wird.

Umstellung von Ressourcen auf Objekte

Mehrere Ressourcen wurden in Objekte umgewandelt. Die Überprüfung des Rückgabewerts mit der Funktion is_resource() sollte durch eine Überprüfung auf false ersetzt werden.

  • Die Funktion curl_init() gibt nun ein CurlHandle-Objekt statt einer Ressource zurück. Die Funktion curl_close() hat keine Wirkung mehr; stattdessen wird die CurlHandle-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktion curl_multi_init() gibt nun ein CurlMultiHandle-Objekt statt einer Ressource zurück. Die Funktion curl_multi_close() hat keine Wirkung mehr; stattdessen wird die CurlMultiHandle-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktion curl_share_init() gibt nun ein CurlShareHandle-Objekt statt einer Ressource zurück. Die Funktion curl_share_close() hat keine Wirkung mehr; stattdessen wird die CurlShareHandle-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktion enchant_broker_init() gibt nun ein EnchantBroker-Objekt statt einer Ressource zurück.

  • Die Funktionen enchant_broker_request_dict() und enchant_broker_request_pwl_dict() geben nun ein EnchantDictionary-Objekt statt einer Ressource zurück.

  • Die Erweiterung GD verwendet nun GdImage-Objekte statt Ressourcen als zugrundeliegende Datenstruktur für Bilder. Die Funktion imagedestroy() hat keine Wirkung mehr; stattdessen wird die GdImage-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktionen openssl_x509_read() und openssl_csr_sign() geben nun ein OpenSSLCertificate-Objekt statt einer Ressource zurück. Die Funktion openssl_x509_free() ist veraltet und hat keine Wirkung mehr; stattdessen wird die OpenSSLCertificate-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktion openssl_csr_new() gibt nun statt einer Ressource ein OpenSSLCertificateSigningRequest-Objekt zurück.

  • Die Funktion openssl_pkey_new() gibt nun ein OpenSSLAsymmetricKey-Objekt statt einer Ressource zurück. Die Funktion openssl_pkey_free() ist veraltet und hat keine Wirkung mehr; stattdessen wird die OpenSSLAsymmetricKey-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktion shmop_open() gibt nun ein Shmop-Objekt statt einer Ressource zurück. Die Funktion shmop_close() hat keine Wirkung mehr und ist veraltet; stattdessen wird die Shmop-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die Funktionen socket_create(),
socket_create_listen(),
socket_accept(),
socket_import_stream(),
socket_addrinfo_connect(),
socket_addrinfo_bind() und
socket_wsaprotocol_info_import() geben nun ein
Socket-Objekt statt einer Ressource zurück.
Die Funktion socket_addrinfo_lookup() gibt nun ein
Array von AddressInfo-Objekten statt Ressourcen
zurück.

  • Die Funktion msg_get_queue() gibt nun ein SysvMessageQueue-Objekt statt einer Ressource zurück.

  • Die Funktion sem_get() gibt nun ein SysvSemaphore-Objekt statt einer Ressource zurück.

  • Die Funktion shm_attach() gibt nun ein SysvSharedMemory-Objekt statt einer Ressource zurück.

  • Die Funktionen xml_parser_create() und xml_parser_create_ns() geben nun ein XMLParser-Objekt statt einer Ressource zurück. Die Funktion xml_parser_free() hat keine Wirkung mehr; stattdessen wird die XMLParser-Instanz automatisch zerstört, wenn sie nicht mehr referenziert wird.

  • Die XMLWriter-Funktionen akzeptieren nun XMLWriter-Objekte statt Ressourcen und geben diese zurück.

  • Die Funktion inflate_init() gibt nun ein InflateContext-Objekt statt einer Ressource zurück.

  • Die Funktion deflate_init() gibt nun ein DeflateContext-Objekt statt einer Ressource zurück.

COM und .Net (Windows)

Die Möglichkeit, Konstanten ohne Berücksichtigung der Groß-/Kleinschreibung aus Typbibliotheken zu importieren, wurde entfernt. Das zweite Argument der Funktion com_load_typelib() kann nicht mehr false sein; com.autoregister_casesensitive kann nicht mehr deaktiviert werden. Das bedeutet, dass #case_insensitive-Markierungen in com.typelib_file ignoriert werden.

CURL

CURLOPT_POSTFIELDS akzeptiert keine Objekte mehr als Arrays. Um ein Objekt als Array zu interpretieren, muss eine explizite Umwandlung mittels (array) durchgeführt werden. Dasselbe gilt auch für andere Optionen, die Arrays akzeptieren.

Datum und Uhrzeit

Die Funktionen mktime() und gmmktime() benötigen nun mindestens einen Parameter. Die Funktion time() kann verwendet werden, um den aktuellen Zeitstempel zu erhalten.

DOM

Nicht implementierte Klassen aus der Erweiterung DOM, die keinerlei Funktion hatten und Testdaten enthielten, wurden entfernt. Diese Klassen wurden auch aus der neuesten Version des des DOM-Standards entfernt:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo
  • DOMStringExtend

Nicht implementierte Methoden aus der Erweiterung DOM, die keinerlei Funktion hatten, wurden entfernt:

  • DOMNamedNodeMap::setNamedItem()
  • DOMNamedNodeMap::removeNamedItem()
  • DOMNamedNodeMap::setNamedItemNS()
  • DOMNamedNodeMap::removeNamedItemNS()
  • DOMText::replaceWholeText()
  • DOMNode::compareDocumentPosition()
  • DOMNode::isEqualNode()
  • DOMNode::getFeature()
  • DOMNode::setUserData()
  • DOMNode::getUserData()
  • DOMDocument::renameNode()

Enchant

  • Die Funktionen enchant_broker_list_dicts(),
enchant_broker_describe() und
enchant_dict_suggest() geben nun ein leeres
Array anstelle von null zurück.

Exif

Die Funktion read_exif_data() wurde entfernt; stattdessen sollte die Funktion exif_read_data() verwendet werden.

Filter

  • Die Flags FILTER_FLAG_SCHEME_REQUIRED und FILTER_FLAG_HOST_REQUIRED für den Filter FILTER_VALIDATE_URL wurden entfernt. scheme und host sind (und waren) immer erforderlich.

  • Die Konstanten INPUT_REQUEST und INPUT_SESSION, die u. a. für die Funktion filter_input() verwendet wurden, wurden entfernt. Sie wurden nie implementiert und ihre Verwendung löste immer eine Warnung aus.

GD

  • Die veraltete Funktion image2wbmp() wurde entfernt.

  • Die veralteten Funktionen png2wbmp() und jpeg2wbmp() wurden entfernt.

  • Bei der Funktion imagecropauto() akzeptiert der Standardparameter mode den Wert -1 nicht mehr. Stattdessen sollte IMG_CROP_DEFAULT verwendet werden.

  • Unter Windows wurde die Datei php_gd2.dll in php_gd.dll umbenannt.

GMP

Die Funktion gmp_random() wurde entfernt. Stattdessen
sollte eine der Funktionen gmp_random_range() und
gmp_random_bits() verwendet werden.

Iconv

iconv-Implementierungen, die errno beim Auftreten von Fehlern nicht korrekt setzen, werden nicht mehr unterstützt.

IMAP

  • Bei der Funktion imap_headerinfo() wurde der nicht verwendete Parameter default_host entfernt.

  • Die Funktion imap_header(), die ein Alias von imap_headerinfo() ist, wurde entfernt.

Funktionen für die Internationalisierung

  • Die veraltete Konstante INTL_IDNA_VARIANT_2003 wurde entfernt.

  • Die veraltete Konstante Normalizer::NONE wurde entfernt.

LDAP

  • Die veralteten Funktionen ldap_sort(),
ldap_control_paged_result() und
ldap_control_paged_result_response() wurden
entfernt.

  • Die Schnittstelle der Funktion ldap_set_rebind_proc() hat sich geändert; der Parameter callback akzeptiert keine leeren Zeichenketten nicht mehr; stattdessen sollte null verwendet werden.

MBString

  • Die Direktive mbstring.func_overload wurde entfernt. Die zugehörigen Konstanten MB_OVERLOAD_MAIL, MB_OVERLOAD_STRING und MB_OVERLOAD_REGEX wurden ebenfalls entfernt. Außerdem wurden in der Funktion mb_get_info() die Einträge "func_overload" und "func_overload_list" entfernt.

  • Die Funktion mb_parse_str() kann nicht mehr ohne Angabe eines Ergebnis-Arrays verwendet werden.

  • Eine Reihe veralteter mbregex-Aliase wurde entfernt. Siehe die folgende Liste, welche Funktionen stattdessen verwendet werden sollten:

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

  • Bei der Funktion mb_ereg_replace() wurde der Modifikator e entfernt. Stattdessen sollte die Funktion mb_ereg_replace_callback() verwendet werden.

  • Wenn bei der Funktion mb_ereg_replace() der Parameter für das Suchmuster keine Zeichenkette ist, wird er nun als Zeichenkette anstelle eines ASCII-Codepunkts interpretiert. Das vorherige Verhalten kann durch einen expliziten Aufruf der Funktion chr() wiederhergestellt werden.

  • Der Parameter needle darf bei den Funktionen
mb_strpos(), mb_strrpos(),
mb_stripos(), mb_strripos(),
mb_strstr(), mb_stristr(),
mb_strrchr() und mb_strrichr() nun
leer sein.

  • Bei der Funktion mb_decode_numericentity() wurde der intern nicht verwendete Parameter is_hex entfernt.

  • Bei der Funktion mb_strrpos() wurde das alte Verhalten bei Übergabe der Kodierung anstelle eines Offsets als dritter Parameter entfernt; stattdessen sollte der Offset 0 explizit als viertes Argument angegeben werden.

  • Die Aliase für die ISO_8859-*-Zeichenkodierungen wurden durch die ISO8859-*-Aliase ersetzt, um die Interoperabilität mit der Erweiterung iconv zu verbessern. Die ISO-8859-Aliase von mbregex mit Unterstrichen (ISO_8859_* und ISO8859_*) wurden ebenfalls entfernt.

  • Die Funktionen mb_ereg() und mb_eregi() geben bei einer gefundenen Übereinstimmung nun den booleschen Wert true zurück. Zuvor gaben sie den Integerwert 1 zurück, wenn der Parameter matches nicht übergeben wurde. Wenn matches übergeben wurde, gaben sie max(1, strlen($matches[0])) zurück.

OCI8

  • Die Klassen OCI-Lob und OCI-Collection wurden umbenannt in OCILob bzw. OCICollection, um die Namenskonformität zu gewährleisten, die in PHP 8 durch die arginfo-Tools für Anmerkungen zum Typ (arginfo type annotation tooling) erzwungen wird.

  • Mehrere Alias-Funktionen wurden als veraltet markiert.

  • Die Funktion oci_internal_debug() und ihr Alias ociinternaldebug() wurden entfernt.

ODBC

  • Die Funktion odbc_connect() verwendet Verbindungen nicht mehr wieder.

  • Bei der Funktion odbc_exec() wurde der nicht verwendete Parameter flags entfernt.

OpenSSL

  • Den Funktionen openssl_seal() und openssl_open() muss nun der Parameter method übergeben werden, da der bisherige Standardwert "RC4" als unsicher eingestuft wird.

Reguläre Ausdrücke (Perl-kompatibel)

Wenn ungültige Escape-Sequenzen übergeben werden, werden sie nicht mehr als Literale interpretiert. Dieses Verhalten erforderte bisher den Modifikator X, der nun ignoriert wird.

PHP Data Objects

  • Der Standardmodus für die Fehlerbehandlung wurde von "silent" auf "exceptions" geändert. Siehe Fehler und Fehlerbehandlung für Details.

  • Die Signaturen einiger PDO-Methoden haben sich geändert:

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO-ODBC

Die php.ini-Direktive pdo_odbc.db2_instance_name wurde entfernt.

PDO-MySQL

Die Methode PDO::inTransaction() meldet nun den tatsächlichen Transaktionsstatus der Verbindung, anstatt einer ungefähren Angabe, die von PDO verwaltet wird. Wenn eine Abfrage mit einem "impliziten Commit" ausgeführt wird, gibt PDO::inTransaction() anschließend false zurück, da die Transaktion nicht mehr aktiv ist.

PostgreSQL

  • Die veraltete pg_connect()-Syntax mit mehreren Parametern anstelle einer Verbindungszeichenkette wird nicht mehr unterstützt.

  • Die veraltete Signatur von pg_lo_import() und pg_lo_export(), die die Verbindung als letzten Parameter übergibt, wird nicht mehr unterstützt. Die Verbindung sollte stattdessen als erster Parameter übergeben werden.

  • Die Funktion pg_fetch_all() gibt für Ergebnismengen mit null Zeilen nun ein leeres Array statt false zurück.

Phar

Um mögliche Sicherheitslücken aufgrund von Objektinstanziierung, Autoloading usw. zu schließen, werden Metadaten, die mit phar verknüpft sind, nicht mehr automatisch deserialisiert.

Reflection

  • Die Signaturen der Methoden

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    wurden geändert in:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Code, der sowohl mit PHP 7 als auch mit PHP 8 kompatibel sein muss, kann die folgenden Signaturen verwenden, um mit beiden Versionen kompatibel zu sein:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • Die Methode ReflectionType::__toString() gibt nun eine vollständige Debug-Darstellung des Typs zurück und ist nicht mehr veraltet. Insbesondere enthält das Ergebnis bei nullbaren Typen den Hinweis, der anzeigt, dass null zugewiesen werden kann. Das Format des Rückgabewertes ist nicht stabil und kann sich zwischen den PHP-Versionen ändern.

  • Die export()-Methoden von Reflection wurden entfernt. Stattdessen können Reflection-Objekte in Zeichenketten umgewandelt werden.

  • Die Methoden ReflectionMethod::isConstructor() und ReflectionMethod::isDestructor() geben nun auch für die Schnittstellenmethoden __construct() und __destruct() true zurück. Zuvor galt dies nur für Methoden von Klassen und Traits.

  • Die Methode ReflectionType::isBuiltin() wurde in die Klasse ReflectionNamedType verschoben. Die Klasse ReflectionUnionType verfügt nicht über diese Methode.

Sockets

  • Bei der Funktion socket_addrinfo_lookup() wurden die veralteten flags AI_IDN_ALLOW_UNASSIGNED und AI_IDN_USE_STD3_ASCII_RULES entfernt.

Standard-PHP-Bibliothek (SPL)

  • Die Methode SplFileObject::fgetss() wurde entfernt.

  • Die Methode SplFileObject::seek() sucht nun immer am Anfang der Zeile. In früheren Versionen wurde zum Anfang der nächsten Zeile gesprungen, wenn als Position >=1 angegeben wurde.

  • Die Methode SplHeap::compare() gibt nun die Signatur einer Methode an. Vererbte Klassen, die diese Methode implementieren, müssen nun eine kompatible Methodensignatur verwenden.

  • Die Methoden SplDoublyLinkedList::push(),
SplDoublyLinkedList::unshift() und
SplQueue::enqueue() geben nun void
statt true zurück.

  • Die Funktion spl_autoload_register() löst nun bei ungültigen Parametern immer einen TypeError aus, daher wird der zweite Parameter do_throw ignoriert und es wird eine Meldung ausgegeben, wenn er auf false gesetzt ist.

  • Die Klasse SplFixedArray implementiert nun IteratorAggregate anstelle von Iterator. Die Methoden SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next() und SplFixedArray::valid() wurden entfernt. Sie wurden durch SplFixedArray::getIterator() ersetzt. Jeder Code, der explizit über SplFixedArray iteriert, muss nun die Methode SplFixedArray::getIterator() verwenden, um einen Iterator zu erhalten. Dies bedeutet, dass SplFixedArray nun problemlos in verschachtelten Schleifen verwendet werden kann.

Standard-Bibliothek

  • Die Funktion assert() wertet Zeichenketten-Parameter nicht mehr aus. Stattdessen werden sie genauso behandelt wie jeder andere Parameter. Statt assert('$a == $b') sollte assert($a == $b) verwendet werden. Außerdem wurden die INI-Direktive assert.quiet_eval und die Konstante ASSERT_QUIET_EVAL entfernt, weil sie keine Wirkung mehr haben.

  • Die Funktion parse_str() kann nicht mehr ohne Angabe eines Ergebnis-Arrays verwendet werden.

  • Der Filter string.strip_tags wurde entfernt.

  • Der Parameter needle der Funktionen strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr() und stristr() wird nun immer als Zeichenkette interpretiert. Zuvor wurde needle als ASCII-Codepunkt interpretiert, wenn es keine Zeichenkette war. Das vorherige Verhalten kann durch einen expliziten Aufruf von chr() wiederhergestellt werden.

  • Bei den Funktionen strpos(),
strrpos(), stripos(),
strripos(), strstr(),
stristr() und strrchr() darf der
Parameter needle nun leer sein.

  • Bei den Funktionen substr(), substr_count(), substr_compare() und iconv_substr() darf der Parameter length nun null sein. Wenn null angegeben wird, verhalten sich die Funktionen so, als ob der Parameter für die Länge nicht angegeben worden wäre. Daher wird in diesem Fall anstelle einer leeren Zeichenkette der Rest der Zeichenkette zurückgegeben.

  • Bei der Funktion array_splice() darf der Parameter length nun null sein. Wenn null angegeben wird, verhält sich die Funktion so, als ob der Parameter nicht angegeben worden wäre. Daher löscht die Funktion in diesem Fall alles von offset bis zum Ende des Arrays.

  • Bei den Funktionen vsprintf(), vfprintf() und vprintf() muss der Parameter args nun ein Array sein. Zuvor wurde jeder Typ akzeptiert.

  • Bei der Funktion password_hash() wird die Option 'salt' nicht mehr unterstützt. Wenn die Option 'salt' verwendet wird, wird eine Warnung erzeugt und das angegebene Salz wird ignoriert und stattdessen ein generiertes Salz verwendet.

  • Die Funktion quotemeta() gibt nun eine leere Zeichenkette zurück, wenn eine leere Zeichenkette übergeben wurde. Zuvor wurde false zurückgegeben.

  • Die folgenden Funktionen wurden entfernt:

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • Die Konstante FILTER_SANITIZE_MAGIC_QUOTES wurde entfernt.

  • Der Aufruf der Funktion implode() mit Parametern in umgekehrter Reihenfolge ($pieces, $glue) wird nicht mehr unterstützt.

  • Die Funktion parse_url() unterscheidet nun zwischen fehlenden und leeren Anfragen und Fragmenten:

    • 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 = ""
    Zuvor waren query und fragment in allen oben genannten Fällen null.

  • Die Funktionen var_dump() und debug_zval_dump() geben Gleitkommazahlen nun aus, indem sie serialize_precision statt precision verwenden. Bei einer Standardkonfiguration bedeutet dies, dass Gleitkommazahlen von diesen Debugging-Funktionen nun mit voller Genauigkeit ausgegeben werden.

  • Wenn das von __sleep() zurückgegebene Array nicht existierende Eigenschaften enthält, werden diese nun stillschweigend ignoriert. Zuvor wurden solche Eigenschaften so serialisiert, als hätten sie den Wert null.

  • Beim Start ist die Standard-Locale nun immer "C". Standardmäßig werden keine Locales von der Umgebung übernommen. Zuvor war LC_ALL auf "C" gesetzt, während LC_CTYPE von der Umgebung übernommen wurde. Allerdings haben einige Funktionen die übernommene Locale ohne expliziten Aufruf von setlocale() nicht berücksichtigt. Ein expliziter Aufruf von setlocale() ist nun immer erforderlich, wenn eine Komponente der Locale von ihrem Standardwert abweichen soll.

  • In der Funktion crypt() wurde der veraltete DES-Fallback entfernt. Wenn ein unbekanntes Salt-Format an crypt() übergeben wird, schlägt die Funktion nun mit *0 fehl, anstatt auf einen schwachen DES-Hash zurückzugreifen.

  • Die Funktion crypt() schlägt bei der Angabe von Runden, die außerhalb des Bereichs für SHA256/SHA512 liegen, nun mit *0 fehl, anstatt auf die nächstgelegene Grenze zu setzen. Dies entspricht dem Verhalten der glibc.

  • Das Ergebnis von Sortierfunktionen kann sich ändern, wenn das Array Elemente enthält, die als gleich bewertet werden.

  • Alle für Callbacks geeigneten Funktionen, bei denen nicht explizit angegeben ist, dass sie per Referenz übergebene Parameter akzeptieren, geben nun eine Warnung aus, wenn eine Callback-Funktion mit Referenz-Parametern verwendet wird. Beispiele sind array_filter() und array_reduce(). Dies war bereits bei den meisten Funktionen der Fall, aber nicht bei allen.

  • Der HTTP-Stream-Wrapper, der von Funktionen wie file_get_contents() verwendet wird, meldet nun HTTP/1.1 statt HTTP/1.0. Dies ändert nichts am Verhalten des Clients, kann aber dazu führen, dass Server anders reagieren. Um das alte Verhalten beizubehalten, muss die Stream-Kontext-Option 'protocol_version' gesetzt werden, z. B.

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • Der Aufruf der Funktion crypt() ohne explizites Salz wird nicht mehr unterstützt. Wenn ein starker Hash mit automatisch generiertem Salz erzeugt werden soll, kann stattdessen password_hash() verwendet werden.

  • Die Funktionen substr(), mb_substr(), iconv_substr() und grapheme_substr() setzen Offsets, die außerhalb einer Zeichenkette liegen, nun einheitlich auf die Grenzen der Zeichenkette. Zuvor wurde in einigen Fällen false anstelle einer leeren Zeichenkette zurückgegeben

  • Unter Windows führen die Funktionen für die Ausführung von Programmen, die die Shell verwenden (proc_open(), exec(), popen() usw.) nun konsequent den Befehl %comspec% /s /c "$commandline" aus, was den gleichen Effekt hat wie die Ausführung von $commandline (ohne zusätzliche Anführungszeichen).

Sysvsem

  • Bei der Funktion sem_get() wurde der Parameter auto_release geändert und akzeptiert nun boolsche Werte (bool) anstelle von ganzen Zahlen (int).

Tidy

  • Bei der Funktion tidy_repair_string() wurde der intern nicht verwendete Parameter use_include_path entfernt.

  • tidy::repairString() und tidy::repairFile() sind nun statische Methoden.

Tokenizer

  • Das Token T_COMMENT enthält keinen abschließenden Zeilenumbruch mehr. Der Zeilenumbruch gehört nun zum nachfolgenden T_WHITESPACE-Token. Es ist wichtig zu beachten, dass auf T_COMMENT nicht immer ein Leerzeichen folgt. Es könnte auch ein T_CLOSE_TAG oder das Ende der Datei folgen.

  • Die Namen innerhalb eines Namensraums werden nun durch die Token T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) und T_NAME_RELATIVE (namespace\Foo\Bar) dargestellt. Das Token T_NS_SEPARATOR wird nur als einfaches Begrenzungszeichen für den Namensraum verwendet. Es ist syntaktisch nur zulässig, wenn es in Verbindung mit einer gruppierten use-Deklaration verwendet wird.

XMLReader

XMLReader::open() und XMLReader::xml() sind nun statische Methoden. Sie können immer noch als Instanzmethoden aufgerufen werden, aber erbende Klassen müssen diese Methoden als statisch deklarieren, wenn sie sie überschreiben.

XML-RPC

Die Erweiterung XML-RPC wurde nach PECL verschoben und ist nicht mehr Teil der PHP-Distribution.

Zip

Die Konstante ZipArchive::OPSYS_Z_CPM wurde entfernt (dieser Name hat einen Tippfehler); stattdessen sollte ZipArchive::OPSYS_CPM verwendet werden.

Zlib

  • Die Funktion gzgetss() wurde entfernt.

  • zlib.output_compression ist für Content-Type: image/* nicht mehr automatisch deaktiviert.

PHP-Test-Suites für Windows

Das Skript zur Durchführung von Tests wurde von run-test.php in run-tests.php umbenannt, damit es dem Namen in php-src entspricht.

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.


Veraltete Features

PHP-Kern

  • Wenn nach einem Parameter mit einem Standardwert ein benötigter folgt, hat der Standardwert keinen Effekt. Mit PHP 8.0.0 ist das veraltet und kann durch das Entfernen des Standardwertes behoben werden, ohne dass Funktionalität verloren geht:

    <?php
    function test($a = [], $b) {} // Vorher
    function test($a, $b) {} // Danach
    ?>

    Eine Ausnahme der Regel stellen Parameter dar, welche der Form Typ $param = null entsprechen, bei welcher die Vorgabe null den Typ implizit nullbar macht. Diese Funktionalität bleibt erhalten, es wird jedoch empfohlen, den Typ explizit nullbar zu machen:

    <?php
    function test(A $a = null, $b) {} // Noch erlaubt
    function test(?A $a, $b) {} // Empfohlen
    ?>

  • Das Aufrufen von get_defined_functions() mit exclude_disabled explizit auf false gesetzt, ist veraltet und hat keine Wirkung mehr. get_defined_functions() erlaubt keine deaktivierten Funktionen mehr.

Enchant

  • enchant_broker_set_dict_path() und enchant_broker_get_dict_path() sind veraltet, da diese Funktionalität in libenchant < 1.5 und libenchant-2 nicht mehr vorhanden ist.

  • enchant_dict_add_to_personal() ist veraltet. enchant_dict_add() ersetzt diese Funktion.

  • enchant_dict_is_in_session() ist veraltet. enchant_dict_is_added() ersetzt diese Funktion.

  • enchant_broker_free() und enchant_broker_free_dict() sind ebenfalls veraltet. Das Objekt kann stattdessen mit unset() gelöscht werden.

  • Die Konstanten ENCHANT_MYSPELL und ENCHANT_ISPELL sind veraltet.

LibXML

libxml_disable_entity_loader() ist veraltet. Da nun jedoch libxml 2.9.0 vorausgesetzt wird, ist das externe Laden von Entitäten garantiert standardmäßig deaktiviert, und diese Funktion wird nicht mehr benötigt, um vor XXE-Angriffen zu schützen, es sei denn, das (immer noch angreifbare) LIBXML_NOENT wird verwendet. In diesem Fall ist es empfehlenswert, den Code unter Verwendung von libxml_set_external_entity_loader() zu überarbeiten, um das Laden externer Entitäten zu unterdrücken.

PGSQL / PDO PGSQL

  • Die Konstante PGSQL_LIBPQ_VERSION_STR nimmt nun den selben Wert an wie PGSQL_LIBPQ_VERSION und ist daher veraltet.

  • Die Funktions-Aliase in der pgsql-Erweiterung sind veraltet. Die folgende Liste zeigt, welche Funktionen stattdessen verwendet werden sollen.

    • pg_errormessage() ? pg_last_error()
    • pg_numrows() ? pg_num_rows()
    • pg_numfields() ? pg_num_fields()
    • pg_cmdtuples() ? pg_affected_rows()
    • pg_fieldname() ? pg_field_name()
    • pg_fieldsize() ? pg_field_size()
    • pg_fieldtype() ? pg_field_type()
    • pg_fieldnum() ? pg_field_num()
    • pg_result() ? pg_fetch_result()
    • pg_fieldprtlen() ? pg_field_prtlen()
    • pg_fieldisnull() ? pg_field_is_null()
    • pg_freeresult() ? pg_free_result()
    • pg_getlastoid() ? pg_last_oid()
    • pg_locreate() ? pg_lo_create()
    • pg_lounlink() ? pg_lo_unlink()
    • pg_loopen() ? pg_lo_open()
    • pg_loclose() ? pg_lo_close()
    • pg_loread() ? pg_lo_read()
    • pg_lowrite() ? pg_lo_write()
    • pg_loreadall() ? pg_lo_read_all()
    • pg_loimport() ? pg_lo_import()
    • pg_loexport() ? pg_lo_export()
    • pg_setclientencoding() ? pg_set_client_encoding()
    • pg_clientencoding() -> pg_client_encoding()

Standard Library

  • Sortierend vergleichende Funktionen welche true oder false zurückgeben, werden nun eine deprecation-Warnung zurückgeben und sollten durch eine Implementation ersetzt werden, welche einen Integer zurückgibt, der kleiner, gleich oder größer als 0 ist.

    <?php
    // Replace
    usort($array, fn($a, $b) => $a > $b);
    // With
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Die Verwendung einer leeren Datei als ZipArchive ist veraltet. Libzip 1.6.0 akzeptiert keine leeren Dateien als ZIP-Archive mehr. Der existierende Workaround wird in der nächsten Version entfernt.

  • Die prozedurale API von Zip ist veraltet. Als Ersatz kann ZipArchive genutzt werden. Die Iteration über alle Entitäten kann durch den Einsatz von ZipArchive::statIndex() und einer for-Schleife erreicht werden:

    <?php
    // Iteration mit der prozedualen API
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
    echo     zip_entry_name($entry);
    }

    // Iteration mit der Objekorientierten API
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
    echo     $entry['name'];
    }
    ?>

Reflection

  • ReflectionFunction::isDisabled() ist veraltet, da es nicht mehr möglich ist, eine ReflectionFunction für eine deaktivierte Funktion zu erstellen. Die Methode gibt nun immer false zurück.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), und
ReflectionParameter::isCallable() sind veraltet.
ReflectionParameter::getType() und die
ReflectionType-APIs sollten stattdessen genutzt werden.

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


Sonstige Änderungen

Änderungen in SAPI-Modulen

Apache2Handler

Das PHP-Modul wurde von php7_module in php_module umbenannt.

Geänderte Funktionen

Reflection

Die Ergebnisse von ReflectionClass::getReflectionConstants() können nun mit dem neuen Parameter filter gefiltert werden. Drei neue Konstanten wurden hinzugefügt, die damit verwendet werden können:

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Standard

Die mathematischen Funktionen abs(), ceil(), floor() und round() berücksichtigen die Direktive strict_types nun korrekt. Zuvor wurde der erste Parameter auch im strikten Typisierungsmodus erzwungen.

Zip

  • Die Methoden ZipArchive::addGlob() und ZipArchive::addPattern() akzeptieren mehr Werte im Parameter-Array options:

    • flags
    • comp_method
    • comp_flags
    • env_method
    • enc_password

  • Die Methoden ZipArchiv::addEmptyDir(),
ZipArchiv::addFile() und
ZipArchive::addFromString() haben den neuen
Parameter flags. Damit können die Namenskodierung
(ZipArchive::FL_ENC_*) und die Ersetzung von
Einträgen (ZipArchive::FL_OVERWRITE) verwaltet
werden.

  • Die Methode ZipArchive::extractTo() stellt nun die Änderungszeit der Dateien wieder her.

Sonstige Änderungen bei Erweiterungen

CURL

  • Die Erweiterung CURL benötigt jetzt mindestens libcurl 7.29.0.

  • Der veraltete Parameter version der Funktion curl_version() wurde entfernt.

Datum und Zeit

Die Klasse DatePeriod implementiert nun IteratorAggregate anstelle von Traversable.

DOM

Die Klassen DOMNamedNodeMap und DOMNodeList implementieren nun IteratorAggregate anstelle von Traversable.

Intl

Die Klassen IntlBreakIterator und ResourceBundle implementieren nun IteratorAggregate anstelle von Traversable.

Enchant

Die Erweiterung enchant verwendet nun standardmäßig libenchant-2, falls verfügbar. libenchant Version 1 wird noch unterstützt, ist aber veraltet und könnte in Zukunft entfernt werden.

GD

  • Der Parameter num_points der Funktionen imagepolygon(), imageopenpolygon() und imagefilledpolygon() ist nun optional, d. h. diese Funktionen können nun entweder mit 3 oder mit 4 Parametern aufgerufen werden. Falls der Parameter weggelassen wird, wird er anhand von count($points)/2 berechnet.

  • Die Funktion imagegetinterpolation() wurde hinzugefügt, um die aktuelle Interpolationsmethode zu ermitteln.

JSON

Die Erweiterung JSON kann nicht mehr deaktiviert werden und ist immer ein integraler Bestandteil eines jeden PHP-Builds, ähnlich wie die Erweiterung date.

MBString

Die Unicode-Datentabellen wurden auf Version 13.0.0 aktualisiert.

PDO

PDOStatement implementiert nun IteratorAggregate anstelle von Traversable.

LibXML

Die minimal erforderliche libxml-Version ist nun 2.9.0. Dies bedeutet, dass das Laden von externen Entities nun garantiert standardmäßig deaktiviert ist und keine zusätzlichen Maßnahmen zum Schutz vor XXE-Angriffen ergriffen werden müssen.

MySQLi / PDO-MySQL

  • Wenn mysqlnd nicht verwendet wird (dies ist die standardmäßige und empfohlene Option), ist die niedrigste unterstützte libmysqlclient-Version nun 5.5.

  • mysqli_result implementiert nun IteratorAggregate anstelle von Traversable.

PGSQL / PDO-PGSQL

Die Erweiterungen PGSQL und PDO-PGSQL benötigen nun mindestens libpq 9.1.

Readline

Der Aufruf von readline_completion_function() vor dem Start der interaktiven Eingabeaufforderung (z. B. in auto_prepend_file) überschreibt nun die standardmäßige Vervollständigungs-Funktion der interaktiven Eingabeaufforderung. Zuvor funktionierte readline_completion_function() nur, wenn sie nach dem Start der interaktiven Eingabeaufforderung aufgerufen wurde.

SimpleXML

SimpleXMLElement implementiert nun RecursiveIterator und übernimmt die Funktionalität von SimpleXMLIterator. SimpleXMLIterator ist eine leere Erweiterung von SimpleXMLElement.

Änderungen bei der Handhabung von INI-Dateien

  • com.dotnet_version ist eine neue INI-Direktive, um die Version des .NET-Frameworks festzulegen, das für dotnet-Objekte verwendet wird.

  • zend.exception_string_param_max_len ist eine neue INI-Direktive, um die maximale Länge einer Zeichenkette in einem Parameter eines stringifizierten Stackstraces festzulegen.

EBCDIC

EBCDIC-Targets werden nicht mehr unterstützt, wobei es eher unwahrscheinlich ist, dass sie überhaupt noch funktionieren.

Performance

  • Der Erweiterung opcache wurde ein Just-In-Time- (JIT) Compiler hinzugefügt.

  • Die Funktion array_slice() durchsucht bei einem Array ohne Lücken nicht mehr das gesamte Array, um den Start-Offset zu finden. Dies kann die Laufzeit der Funktion bei großen Offsets und kleinen Längen erheblich reduzieren.

  • Wenn die Locale von LC_CTYPE "C" ist (was der Standard ist), verwendet die Funktion strtolower() nun die SIMD-Implementierung.

User Contributed Notes

barry dot nelson at amobiledevice dot com 16-Jan-2023 12:18
If loading the PHP8 apache module on SuSe Linux, the configuration scripts incorrectly try to load it with automatically generated load statement of:
LoadModule php8_module                     /usr/lib64/apache2/mod_php8.so
This does not work, the patch below fixes the conf file generator...

--- /usr/share/apache2/get_module_list    2023-01-14 22:41:49.586825349 -0500
+++ /usr/share/apache2/get_module_list    2023-01-14 22:42:02.171600410 -0500
@@ -91,4 +91,8 @@
     esac

+    if [ "$module_id" = "php8_module" ]; then
+        module_id="php_module"
+    fi
+
     if [[ -f $module_path ]]; then
         printf "LoadModule %-30s %s\n" $module_id $module_path >&3


Migration von PHP 7.3.x auf PHP 7.4.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Klassen und Interfaces
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Entfernte Erweiterungen
  • Sonstige Änderungen
  • Windows-Unterstützung

Diese neue Minor-Version bringt eine Reihe von neuen Features und einige wenige Inkompatibilitäten, die vor der Umstellung der PHP-Versionen in der Produktivumgebung getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.0.x, 7.1.x, 7.2.x und 7.3.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

PHP-Kern

Typisierte Eigenschaften

Klasseneigenschaften unterstützen nun Typ-Deklarationen.

<?php
class User {
public int $id;
public string $name;
}
?>
Das obige Beispiel erzwingt, dass $user->id nur int-Werte zugewiesen werden können und $user->name nur string-Werte.

Pfeilfunktionen

Die Pfeilfunktionen bieten eine Kurzform der Syntax für die Definition von Funktionen mit impliziter Bindung an den Wertebereich.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Eingeschränkte Kovarianz des Rückgabetyps und Kontravarianz des Parametertyps

Der folgende Code funktioniert nun:

<?php
class A {}
class B extends A {}

class Producer {
public function method(): A {}
}
class ChildProducer extends Producer {
public function method(): B {}
}
?>
Die vollständige Unterstützung der Varianz ist nur verfügbar, wenn automatisches Laden verwendet wird. Innerhalb einer einzelnen Datei sind nur nichtzyklische Typreferenzen möglich, da alle Klassen verfügbar sein müssen, bevor sie referenziert werden.

Zuweisungsoperator für die Kombination mit null (null-Koaleszenz)

<?php
$array['key'] ??= computeDefault();
// entspricht in etwa
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
?>

Entpacken innerhalb von Arrays

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Trennzeichen für numerische Literale

Bei numerischen Literalen können nun Unterstriche zwischen den Ziffern eingefügt werden.

<?php
6.674_083e-11; // Gleitkommazahl
299_792_458; // Dezimalzahl
0xCAFE_F00D; // Hexadezimalzahl
0b0101_1111; // Binärzahl
?>

Schwache Referenzen

Eine schwache Referenz ermöglicht es dem Programmierer, eine Referenz auf ein Objekt zu behalten, die nicht verhindert, dass das Objekt zerstört wird.

Zulassen von Exceptions aus __toString()

Bei der Methode __toString() ist es nun möglich, Exceptions auszulösen. Zuvor führte dies zu einem schwerwiegenden Fehler. Alle behebbaren schwerwiegenden Fehler bei Zeichenketten-Konvertierungen wurden in Error-Exceptions umgewandelt.

CURL

Wenn die Erweiterung mit libcurl >= 7.56.0 kompiliert wurde, unterstützt die Klasse CURLFile nun zusätzlich zu einfachen Dateinamen auch Stream-Wrapper.

Filter

Der Filter FILTER_VALIDATE_FLOAT unterstützt nun die Optionen min_range und max_range mit der gleichen Semantik wie FILTER_VALIDATE_INT.

FFI

FFI ist eine neue Erweiterung, die eine einfache Möglichkeit bietet, native Funktionen aufzurufen, auf native Variablen zuzugreifen und Datenstrukturen zu erzeugen/aufzurufen, die in C-Bibliotheken definiert sind.

GD

Der Bildfilter IMG_FILTER_SCATTER wurde hinzugefügt, um einen Streufilter auf Bilder anzuwenden.

Hash

Der crc32c-Hash, der das Castagnoli-Polynom verwendet, wurde hinzugefügt. Diese CRC32-Variante wird in Speichersystemen wie iSCSI, SCTP, Btrfs und ext4 verwendet.

Multibyte-Zeichenketten

Die Funktion mb_str_split() wurde hinzugefügt. Sie bietet die gleiche Funktionalität wie str_split(), arbeitet aber mit Codepunkten anstelle von Bytes.

OPcache

Die Unterstützung für das Vorladen von Code wurde hinzugefügt.

Reguläre Ausdrücke (Perl-kompatibel)

Die Funktionen preg_replace_callback() und preg_replace_callback_array() akzeptieren nun zusätzlich den Parameter flags, der die Flags PREG_OFFSET_CAPTURE und PREG_UNMATCHED_AS_NULL unterstützt. Dies beeinflusst das Format des Arrays für die Übereinstimmungen, das an die Callback-Funktion übergeben wird.

PDO

Bei den Treibern für mysql, mssql, dblib, firebird und oci können Benutzername und Passwort nun als Teil des PDO DSN angegeben werden. Zuvor wurde dies nur vom pgsql-Treiber unterstützt. Wenn ein Benutzername/Passwort sowohl im Konstruktor als auch im DSN angegeben wird, hat der Konstruktor Vorrang.

Es ist nun möglich, Fragezeichen in SQL-Abfragen zu maskieren, damit sie nicht als als Platzhalter für Parameter interpretiert werden. Mit ?? ist es möglich, ein einzelnes Fragezeichen an die Datenbank zu senden. Dieses kann z. B. bei PostgreSQL als ?-Operator verwendet werden, um zu prüfen, ob ein JSON-Schlüssel existiert.

PDO_OCI

Die Methode PDOStatement::getColumnMeta() ist nun verfügbar.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) ermöglicht es, zu prüfen, ob eine Anweisung nur lesend ist, d. h., ob sie die Datenbank nicht verändert.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true)
ermöglicht in PDO::errorInfo() und
PDOStatement::errorInfo() die Verwendung der erweiterten
SQLite3-Ergebniscodes.

SQLite3

Die Methode SQLite3::lastExtendedErrorCode() wurde hinzugefügt, um den letzten erweiterten Ergebniscode abzurufen.

SQLite3::enableExtendedResultCodes($enable = true) wurde hinzugefügt, was dazu führt, dass SQLite3::lastErrorCode() erweiterte Ergebniscodes zurückgibt.

Standard

strip_tags() mit einem Array von Tag-Namen

Die Funktion strip_tags() akzeptiert nun auch ein Array mit erlaubten Tags: Anstelle von strip_tags($str, '<a><p>') kann nun strip_tags($str, ['a', 'p']) geschrieben werden.

Benutzerdefinierte Serialisierung von Objekten

Es wurde ein neues Verfahren für die benutzerdefinierte Serialisierung von Objekten hinzugefügt, das zwei neue magische Methoden verwendet: __serialize und __unserialize.

<?php
// Gibt ein Array zurück, das alle notwendigen Zustände des Objekts enthält.
public function __serialize(): array;

// Stellt den Objektzustand aus dem angegebenen Datenarray wieder her.
public function __unserialize(array $data): void;
?>
Das neue Serialisierungsverfahren ersetzt die Schnittstelle Serializable, die in Zukunft für veraltet erklärt werden wird.

Verwendung der array_merge-Funktionen ohne Parameter

Die Funktionen array_merge() und array_merge_recursive() können nun auch ohne Parameter aufgerufen werden und geben in diesem Fall ein leeres Array zurück. Dies ist nützlich in Verbindung mit dem Spread-Operator (Zerlegungsoperator), z. B. array_merge(...$arrays).

Die Funktion proc_open()

proc_open() akzeptiert für den Befehl nun ein Array anstelle einer Zeichenkette. In diesem Fall wird der Prozess direkt geöffnet (ohne den Umweg über eine Shell) und PHP kümmert sich bei Bedarf darum, die Parameter zu maskieren.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() unterstützt nun die Deskriptoren redirect und null.

<?php
// Wie 2>&1 in der Shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Wie 2>/dev/null oder 2>nul in der Shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) ohne libargon

Wenn PHP ohne libargon gebaut wird, hat password_hash() nun die argon2i- und argon2id-Implementierungen aus der Erweiterung Sodium.

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.


Neue Klassen und Interfaces

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


Neue Funktionen

PHP-Kern

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


Neue globale Konstanten

PHP-Kern

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

Die folgenden FreeBSD-spezifischen Socket-Optionen wurden hinzugefügt:

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


Nicht abwärtskompatible Änderungen

PHP-Kern

Zugriff auf Nicht-Arrays im Array-Stil

Der Versuch, Werte vom Typ null, bool, int, float oder resource wie ein Array zu verwenden, (z. B. $null["key"]) erzeugt nun einen Hinweis.

Die Funktion get_declared_classes()

get_declared_classes() gibt keine anonymen Klassen mehr zurück, die noch nicht instanziiert wurden.

Das Schlüsselwort fn

fn ist nun ein reserviertes Schlüsselwort. Insbesondere kann es nicht mehr als Funktions- oder Klassenname verwendet werden. Es kann weiterhin als Name einer Methode oder Klassenkonstante verwendet werden.

<?php-Tag am Ende der Datei

Das Tag <?php am Ende der Datei (ohne nachgestellten Zeilenumbruch) wird nun als ein öffnendes PHP-Tag interpretiert. Zuvor wurde es entweder als kurzes öffnendes Tag gefolgt vom Literal php interpretiert und führte zu einem Syntaxfehler (bei short_open_tag=1) oder es wurde als literale Zeichenkette <?php interpretiert (bei short_open_tag=0).

Stream-Wrapper

Wenn include/require für einen Stream verwendet wird, wird streamWrapper::stream_set_option() mit der Option STREAM_OPTION_READ_BUFFER aufgerufen. Bei einem benutzerdefinierten Stream-Wrapper kann es notwendig sein, die Methode streamWrapper::stream_set_option() zu implementieren, um eine Warnung zu vermeiden (eine Implementierung, die immer false zurückgibt, ist normalerweise ausreichend).

Serialisierung

Das Serialisierungsformat o wurde entfernt. Da es von PHP nie erzeugt wurde, kann dies nur die Deserialisierung von manuell erstellten Zeichenketten beeinträchtigen.

Konstanten für den Passwort-Algorithmus

Die Bezeichner der Algorithmen für das Hashing von Passwörtern sind nun keine Ganzzahlen mehr, sondern nullbare Zeichenketten.

  • PASSWORD_DEFAULT war int 1 und ist nun '2y' (in PHP 7.4.0, 7.4.1 und 7.4.2 war es null)
  • PASSWORD_BCRYPT war int 1 und ist nun '2y'
  • PASSWORD_ARGON2I war int 2 und ist nun 'argon2i'
  • PASSWORD_ARGON2ID war int 3 und ist nun 'argon2id'

Anwendungen, die die Konstanten PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I und PASSWORD_ARGON2ID korrekt verwenden, werden weiterhin korrekt funktionieren.

Die Funktion htmlentities()

htmlentities() erzeugt nun einen Hinweis (anstelle einer Warnung wegen strikter Standards), wenn sie mit einer Kodierung verwendet wird, bei der nur die Substitution von Basisentitäten unterstützt wird. In diesem Fall entspricht das der Funktion htmlspecialchars().

Die Funktionen fread() und fwrite()

fread() und fwrite() geben nun false zurück, wenn die Operation fehlgeschlagen ist; zuvor wurde eine leere Zeichenkette oder 0 zurückgegeben. EAGAIN/EWOULDBLOCK werden nicht als Fehler gewertet.

Diese Funktionen geben nun auch bei Fehlern eine Meldung aus, z. B. wenn versucht wird, in eine schreibgeschützte Dateiressource zu schreiben.

BCMath mathematische Berechnungen mit beliebiger Genauigkeit

BCMath-Funktionen erzeugen nun eine Warnung, wenn eine nicht wohlgeformte Zahl übergeben wird, z. B. "32foo". Der Parameter wird wie bisher als Null interpretiert.

CURL

Der Versuch, eine CURLFile-Klasse zu serialisieren, erzeugt nun eine Exception. Zuvor wurde die Exception nur bei der Deserialisierung ausgelöst.

Die Verwendung von CURLPIPE_HTTP1 ist veraltet und wird ab cURL 7.62.0 nicht mehr unterstützt.

Bei der Funktion curl_version() ist der Parameter $version veraltet. Wenn ein anderer Wert als der Standardwert CURLVERSION_NOW übergeben wird, wird eine Warnung ausgegeben und der Parameter wird ignoriert.

Datum und Uhrzeit

Der Aufruf von var_dump() oder ähnlichem mit einer Instanz von DateTime oder DateTimeImmutable hinterlässt keine verfügbaren Eigenschaften des Objekts mehr.

Der Vergleich von DateInterval-Objekten (mittels ==, < usw.) erzeugt nun eine Warnung und gibt immer false zurück. Zuvor wurden alle DateInterval-Objekte als gleich angesehen, sofern sie keine Eigenschaften hatten.

Intl

Bei den Funktionen idn_to_ascii() und idn_to_utf8() ist der Standardwert des Parameters nun INTL_IDNA_VARIANT_UTS46 anstelle des veralteten INTL_IDNA_VARIANT_2003.

MySQLi

Die integrierte Serverfunktionalität wurde entfernt. Sie war seit mindestens PHP 7.0 fehlerhaft.

Die undokumentierte Eigenschaft mysqli::$stat wurde zugunsten von mysqli::stat() entfernt.

OpenSSL

Die Funktion openssl_random_pseudo_bytes() löst nun ähnlich wie random_bytes() bei Fehlern eine Exception aus. Insbesondere wird ein Error ausgelöst, wenn die Anzahl der angeforderten Bytes kleiner oder gleich Null ist, und eine Exception wird ausgelöst, wenn nicht genügend Zufallsdaten gesammelt werden können. Wenn die Funktion keine Exception wirft, ist der Ausgabeparameter $crypto_strong garantiert immer true, weshalb eine explizite Überprüfung nicht nötig ist.

Reguläre Ausdrücke (Perl-kompatibel)

Wenn der Modus PREG_UNMATCHED_AS_NULL verwendet wird, werden nicht gefundene Teilsuchmuster nun auch auf null gesetzt (oder [null, -1], wenn die Erfassung des Offsets aktiviert ist). Das bedeutet, dass die Größe der $matches (Übereinstimmungen) immer gleich ist.

PHP-Datenobjekte (PDO)

Der Versuch, eine Instanz von PDO oder PDOStatement zu serialisieren, erzeugt nun eine Exception anstelle einer PDOException, was dem Verhalten anderer interner Klassen entspricht, die keine Serialisierung unterstützen.

Reflection

Reflection-Objekte erzeugen nun eine Exception, wenn versucht wird, sie zu serialisieren. Die Serialisierung von Reflection-Objekten wurde nie unterstützt und führte zu beschädigten Reflection-Objekten. Sie ist nun ausdrücklich verboten.

Die Werte der Klassenkonstanten von ReflectionClassConstant, ReflectionMethod und ReflectionProperty haben sich geändert.

Standard-PHP-Bibliothek (SPL)

Wenn die Funktion get_object_vars() für eine Instanz von ArrayObject aufgerufen wird, gibt sie nun immer die Eigenschaften der Klasse ArrayObject selbst (oder einer Unterklasse) zurück. Zuvor wurden die Werte des betreffenden Arrays/Objekts zurückgegeben, es sei denn, das Flag ArrayObject::STD_PROP_LIST wurde angegeben.

Andere betroffene Operationen sind:

  • Die Methode ReflectionObject::getProperties()
  • Die Funktionen reset(), current() usw. Stattdessen sollten die Methoden von Iterator verwendet werden.
  • Möglicherweise andere, die Objekteigenschaften als Liste bearbeiten, z. B. die Funktion array_walk().

Typumwandlungen mit (array) sind davon nicht betroffen. Sie geben weiterhin entweder das betreffende Array oder die Eigenschaften der Klasse ArrayObject zurück, je nachdem ob das Flag ArrayObject::STD_PROP_LIST verwendet wird.

Die Methode SplPriorityQueue::setExtractFlags() löst eine Exception aus, wenn Null (0) übergeben wird. Zuvor erzeugte dies bei der nächsten Extraktionsoperation einen behebbaren schwerwiegenden Fehler.

Die Klassen ArrayObject, ArrayIterator, SplDoublyLinkedList und SplObjectStorage unterstützen nun zusätzlich zur Schnittstelle Serializable das Verfahren __serialize() und __unserialize(). Das bedeutet, dass die mit älteren PHP-Versionen serialisierten Daten immer noch deserialisiert werden können, aber Daten, die mit PHP 7.4 erstellt wurden, von älteren Versionen nicht verstanden werden.

Tokenizer

Die Funktion token_get_all() gibt für unerwartete Zeichen nun ein T_BAD_CHARACTER-Token aus, anstatt Löcher im Token-Stream zu hinterlassen.

Eingehende Cookies

Seit PHP 7.4.11 werden die Namen der eingehenden Cookies aus Sicherheitsgründen nicht mehr URL-dekodiert.

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


Veraltete Features

PHP-Kern

Verschachtelte ternäre Operatoren ohne explizite Klammern

Verschachtelte ternäre Operationen müssen nun explizit Klammern verwenden, um die Reihenfolge der Operationen festzulegen. Wenn in der Vergangenheit keine Klammern verwendet wurden, führte die Links-Assoziativität in den meisten Fällen nicht zum erwarteten Verhalten.

<?php
1 ? 2 : 3 ? 4 : 5; // veraltet
(1 ? 2 : 3) ? 4 : 5; // OK
1 ? 2 : (3 ? 4 : 5); // OK
?>

Klammern sind nicht erforderlich, wenn der mittlere Operand umschlossen wird, da dies immer eindeutig ist und nicht durch die Assoziativität beeinflusst wird:

1 ? 2 ? 3 : 4 : 5 // OK

Zugriff auf Array- und Zeichenketten-Offset mit geschweiften Klammern

Die Syntax für den Zugriff auf Array- und String-Offsets mit geschweiften Klammern ist veraltet. Statt $var{$idx} sollte $var[$idx] verwendet werden.

Die Typumwandlung (real) und die Funktion is_real()

Die Typumwandlung (real) ist veraltet, stattdessen (float) verwendet werden.

Die Funktion is_real() ist ebenfalls veraltet, stattdessen sollte is_float() verwendet werden.

Aufhebung der Bindung von $this, wenn $this verwendet wird

Die Bindung von $this an eine nicht-statische Closure aufzuheben, die $this verwendet, ist veraltet.

Schlüsselwort parent ohne übergeordnete Klasse

Die Verwendung von parent innerhalb einer Klasse ohne Elternklasse ist veraltet und wird in Zukunft einen Fehler bei der Kompilierung auslösen. Derzeit wird ein Fehler nur dann erzeugt, wenn zur Laufzeit auf die Elternklasse zugegriffen wird.

INI-Option allow_url_include

Die INI-Direktive allow_url_include ist veraltet. Wenn sie aktiviert ist, wird beim Start ein entsprechender Hinweis erzeugt.

Ungültige Zeichen in Funktionen zur Umwandlung der Basis

Die Übergabe unzulässiger Zeichen an die Funktionen base_convert(), bindec(), octdec() und hexdec() führt nun zu einem Hinweis auf eine veraltete Verwendung. Das Ergebnis wird so berechnet, als gäbe es das unzulässige Zeichen nicht. Führende und nachfolgende Leerzeichen sowie Präfixe wie 0x (je nach Zahlensystem) sind weiterhin zulässig.

Die Anwendung von array_key_exists() auf Objekte

Die Anwendung der Funktion array_key_exists() auf Objekte ist veraltet. Stattdessen sollte entweder isset() oder property_exists() verwendet werden.

Funktionen für "magische Anführungszeichen" (Magic Quotes)

Die Funktionen get_magic_quotes_gpc() und get_magic_quotes_runtime() sind veraltet. Sie geben immer false zurück.

Die Funktion hebrevc()

Die Funktion hebrevc() ist veraltet. Sie kann durch nl2br(hebrev($str)) ersetzt werden oder, besser, indem die Unterstützung von Unicode-RTL genutzt wird.

Die Funktion convert_cyr_string()

Die Funktion convert_cyr_string() ist veraltet. Sie
kann durch mb_convert_string(),
iconv() oder UConverter ersetzt
werden.

Die Funktion money_format()

Die Funktion money_format() ist veraltet. Sie kann durch die Funktionalität der intl-Klasse NumberFormatter ersetzt werden.

Die Funktion ezmlm_hash()

Die Funktion ezmlm_hash() ist veraltet.

Die Funktion restore_include_path()

Die Funktion restore_include_path() ist veraltet. Sie kann durch ini_restore('include_path') ersetzt werden.

Reihenfolge der Parameter bei implode()

Die Übergabe von Parametern an die Funktion implode() in umgekehrter Reihenfolge ist veraltet, statt implode($parts, $glue) sollte implode($glue, $parts) verwendet werden.

COM

Der Import von Typbibliotheken, bei denen die Groß- und Kleinschreibung von Konstanten nicht beachtet wird, ist veraltet.

Filter

Der Filter FILTER_SANITIZE_MAGIC_QUOTES ist veraltet, stattdessen sollte FILTER_SANITIZE_ADD_SLASHES verwendet werden.

Multibyte-Zeichenketten

Bei der Funktion mb_ereg_replace() ist die Übergabe eines Musters, das keine Zeichenkette ist, veraltet. Gegenwärtig werden solche Muster als ASCII-Codepunkte interpretiert. In PHP 8 wird das Muster stattdessen als Zeichenkette interpretiert.

Bei der Funktion mb_strrpos() ist die Übergabe der Kodierung als 3. Parameter veraltet. Stattdessen sollten ein 0-Offset und die Kodierung als 4. Parameter übergeben werden.

Lightweight Directory Access Protocol (LDAP)

Die Funktionen ldap_control_paged_result_response() und ldap_control_paged_result() sind veraltet. Steuerelemente für die Seitennavigation können stattdessen zusammen mit ldap_search() gesendet werden.

Reflection

Der Aufruf von ReflectionType::__toString() erzeugt nun einen Hinweis auf eine veraltete Funktion. Diese Methode wird in der Dokumentation seit PHP 7.1 als veraltet zugunsten von ReflectionNamedType::getName() bezeichnet, hat aber aus technischen Gründen keinen entsprechenden Hinweis erzeugt.

Die export()-Methoden sind in allen Klassen von Reflection veraltet. Stattdessen sollte ein Reflection-Objekt erzeugt werden und dieses in eine Zeichenkette umgewandelt werden:

<?php
// Anstelle von ReflectionClass::export(Foo::class, false):
echo new ReflectionClass(Foo::class), "\n";

// Anstelle von $str = ReflectionClass::export(Foo::class, true):
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

Bei der Funktion socket_addrinfo_lookup() sind die Flags AI_IDN_ALLOW_UNASSIGNED und AI_IDN_USE_STD3_ASCII_RULES veraltet und entsprechen damit der zugrundeliegenden 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


Entfernte Erweiterungen

Diese Erweiterungen wurden nach PECL verschoben und sind nicht mehr Teil der PHP-Distribution. Die PECL-Paketversionen dieser Erweiterungen werden entsprechend der Benutzernachfrage erstellt.

  • Firebird/Interbase Der Zugang zu einer InterBase- und/oder Firebird-basierten Datenbank ist nach wie vor mit dem PDO Firebird-Treiber verfügbar.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


Sonstige Änderungen

Verbesserung der Leistung

PHP-Kern

Für die Funktion array_key_exists() wurde ein spezieller VM-Opcode hinzugefügt, der die Leistung dieser Funktion verbessert, wenn der Parameterwert statisch aufgelöst werden kann. In Code, der Namensräume verwendet, kann es notwendig sein, einen absoluten Namen zu verwenden (\array_key_exists()) oder die Funktion explizit zu importieren.

Reguläre Ausdrücke (Perl-kompatibel)

Wenn die Funktion preg_match() im UTF-8 Modus (Modifikator "u") mehrmals für dieselbe Zeichenkette aufgerufen wird (aber möglicherweise mit unterschiedlichen Offsets), wird sie nur einmal auf valides UTF-8 geprüft.

Änderungen bei der Handhabung von INI-Dateien

zend.exception_ignore_args ist eine neue INI-Direktive, um Parameter in die von Ausnahmen erzeugten Stacktraces einzubeziehen oder davon auszuschließen.

opcache.preload_user ist eine neue INI-Direktive, um das Benutzerkonto anzugeben, unter dem der vorab geladene Code ausgeführt wird, wenn er sonst unter root laufen würde (was aus Sicherheitsgründen nicht erlaubt ist).

Umstellung auf pkg-config

Eine Reihe von Erweiterungen wurde dahingehend umgestellt, dass sie für die Erkennung von Bibliotheksabhängigkeiten ausschließlich pkg-config verwenden. Im Allgemeinen bedeutet dies, dass statt --with-foo-dir=DIR oder ähnlich nur --with-foo verwendet wird. Benutzerdefinierte Bibliothekspfade können entweder angegeben werden, imdem zusätzliche Verzeichnisse zu PKG_CONFIG_PATH hinzugefügt werden, oder durch Angabe expliziter Kompilierungsoptionen mittels FOO_CFLAGS und FOO_LIBS.

Die folgenden Erweiterungen und SAPIs sind betroffen:

  • CURL:
    • --with-curl akzeptiert kein Verzeichnis mehr.
  • Enchant:
    • --with-enchant akzeptiert kein Verzeichnis mehr.
  • FPM:
    • --with-fpm-systemd verwendet nur noch pkg-config für libsystemd-Überprüfungen. Die erforderliche Mindestversion von libsystemd ist 209.
  • GD:
    • --with-gd wurde zu --enable-gd (ob das Modul aktiviert werden soll oder nicht) und --with-external-gd (um eine externe libgd zu verwenden, anstatt der mitgelieferten).
    • --with-png-dir wurde entfernt. libpng wird nun zwingend vorausgesetzt.
    • --with-zlib-dir wurde entfernt. zlib wird nun zwingend vorausgesetzt.
    • --with-freetype-dir wurde zu --with-freetype
    • --with-jpeg-dir wurde zu --with-jpeg
    • --with-webp-dir wurde zu --with-webp
    • --with-xpm-dir wurde zu --with-xpm
  • IMAP:
    • --with-kerberos-systemd akzeptiert kein Verzeichnis mehr.
  • Intl:
    • --with-icu-dir wurde entfernt. Falls --enable-intl übegeben wird, dann wird libicu immer zwingend vorausgesetzt.
  • LDAP:
    • --with-ldap-sasl akzeptiert kein Verzeichnis mehr.
  • Libxml:
    • --with-libxml-dir wurde entfernt.
    • --enable-libxml wurde zu --with-libxml.
    • --with-libexpat-dir wurde umbenannt in --with-expat und akzeptiert kein Verzeichnis mehr.
  • Litespeed:
    • --with-litespeed wurde zu --enable-litespeed.
  • Mbstring:
    • --with-onig wurde entfernt. Sofern --disable-mbregex nicht übergeben wurde, ist libonig zwingend erforderlich.
  • ODBC:
    • --with-iodbc akzeptiert kein Verzeichnis mehr.
    • --with-unixODBC ohne Verzeichnis verwendet nun pkg-config (bevorzugt). Das Verzeichnis wird bei älteren Versionen ohne libodbc.pc immer noch akzeptiert.
  • OpenSSL:
    • --with-openssl akzeptiert kein Verzeichnis mehr.
  • PCRE:
    • --with-pcre-regex wurde entfernt. Dafür steht --with-external-pcre zur Verfügung, um statt der mitgelieferten PCRE-Bibliothek eine externe zu verwenden
  • PDO_SQLite:
    • --with-pdo-sqlite akzeptiert kein Verzeichnis mehr.
  • Readline:
    • --with-libedit akzeptiert kein Verzeichnis mehr.
  • Sodium:
    • --with-sodium akzeptiert kein Verzeichnis mehr.
  • SQLite3:
    • --with-sqlite3 akzeptiert kein Verzeichnis mehr.
  • XSL:
    • --with-xsl akzeptiert kein Verzeichnis mehr.
  • Zip:
    • --with-libzip wurde entfernt.
    • --enable-zip wurde zu --with-zip.

Maskieren von CSV

fputcsv(), fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv() und
SplFileObject::setCsvControl() akzeptieren nun
eine leere Zeichenkette als $escape-Parameter, wodurch
der proprietäre PHP-Mechanismus für die Maskierung deaktiviert wird.

Das Verhalten der Funktion str_getcsv() wurde entsprechend angepasst (bisher war eine leere Zeichenkette gleichbedeutend mit der Verwendung der Standardeinstellung).

Die Methode SplFileObject::getCsvControl() kann dementsprechend für das dritte Array-Element nun auch eine leere Zeichenkette zurückgeben.

Datenfilterung

Für die Erweiterung filter steht die Option --with-pcre-dir für Unix-Builds nicht mehr zur Verfügung; sie kann nun problemlos mit ./configure als Shared gebaut werden.

GD

Das Verhalten der Funktion imagecropauto() in der mitgelieferten libgd-Bibliothek wurde mit dem der libgd des Systems synchronisiert:

  • IMG_CROP_DEFAULT greift nicht mehr auf IMG_CROP_SIDES zurück.
  • Der Schwellenwert für das Cropping verwendet nun den Algorithmus der System-libgd.

Bei der Funktion imagecropauto() wurde der Standardparameter von $mode geändert auf IMG_CROP_DEFAULT; die Übergabe von -1 ist veraltet.

Die Funktion imagescale() unterstützt nun die Beibehaltung des Seitenverhältnisses, wenn auf eine feste Höhe skaliert wird, indem -1 als $new_width übergeben wird.

HASH Message Digest Framework

Die Erweiterung hash kann nicht mehr deaktiviert werden und ist, ähnlich wie die Erweiterung date, immer ein integraler Bestandteil eines jeden PHP-Builds.

Intl

Die Erweiterung intl benötigt nun mindestens ICU 50.1.

Die Klasse ResourceBundle implementiert nun Countable.

Lightweight Directory Access Protocol (LDAP)

Die Unterstützung für nsldap und umich_ldap wurde entfernt.

Libxml

Alle libxml-basierten Erweiterungen benötigen nun mindestens libxml 2.7.6.

Multibyte-Zeichenketten

Die Bibliothek oniguruma wird nicht mehr in PHP mitgeliefert, stattdessen muss libonig auf dem System verfügbar sein. Alternativ dazu kann die Option --disable-mbregex verwendet werden, um die Komponente mbregex zu deaktivieren.

OPcache

Die Konfigurationsoptionen --disable-opcache-file und --enable-opcache-file wurden zugunsten der INI-Direktive opcache.file_cache entfernt.

Passwort-Hashing

Die Funktionen password_hash() und password_needs_rehash() akzeptieren beim Parameter $algo nun nullbare String und Integer.

PEAR

Die Installation von PEAR (einschließlich PECL) ist nicht mehr standardmäßig aktiviert. Sie kann explizit mit der Option --with-pear aktiviert werden. Diese Option ist veraltet und wird möglicherweise in Zukunft entfernt.

Reflection

Bei den Klassen ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject und ReflectionProperty haben sich die numerischen Werte der Modifizierungskonstanten (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC und IS_STATIC) geändert.

SimpleXML

Die Klasse SimpleXMLElement implementiert nun Countable.

SQLite3

Die mitgelieferte Bibliothek libsqlite wurde entfernt. Um die Erweiterung SQLite3 zu erstellen, wird nun libsqlite3 = 3.7.4 benötigt. Um die Erweiterung PDO_SQLite zu erstellen, wird nun libsqlite3 = 3.5.0 benötigt.

Es ist nun ausdrücklich verboten, SQLite3, SQLite3Stmt und SQLite3Result zu serialisieren und zu deserialisieren. Zuvor war es zwar möglich, die Instanzen dieser Klassen zu serialisieren, aber die Deserialisierung führte zu unbrauchbaren Objekten.

Die Notation @param kann nun auch verwendet werden, um SQL-Abfrageparameter anzugeben.

Zip

Die mitgelieferte Bibliothek libzip wurde entfernt. Um die Erweiterung zip zu erstellen, wird nun libzip >= 0.11 benötigt.

User Contributed Notes

santi at mola dot io 31-Jul-2020 07:54
Note for internals/extensions:

Many opcode values changed between PHP 7.3 and 7.4, so most documentation resources are outdated in that regard. You can look the definitions at Zend/zend_vm_opcodes.h in php-src. For example, ZEND_ECHO changes from 40 to 136.

While opcode changes happen in a lot of PHP versions, the change in 7.4 is quite significant.
ohcc at 163 dot com 09-Jun-2020 04:56
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
Florent H (Sowapps) 16-Feb-2020 07:37
This version brings an important changes with the directive zend.exception_ignore_args set to On by default.
In all stack traces, the args key is now missing.
All php frameworks have to handle this to report errors & exceptions.


Windows-Unterstützung

configure-Flags

configure berücksichtigt nun zusätzlich die Umgebungsvariablen CFLAGS und LDFLAGS.

Behandlung von CTRL

Es ist nun möglich, die Tastenkombinationen CTRL+C und CTRL+BREAK auf der Konsole abzufangen, indem mit der Funktion sapi_windows_set_ctrl_handler() ein Handler definiert wird.

Unter Windows kann der Funktion proc_open() nun die Option "create_process_group" übergeben werden. Dies ist erforderlich, wenn der Kindprozess CTRL-Ereignisse verarbeiten soll.

OPcache

OPcache unterstützt nun über die die INI-Anweisung opcache.cache_id eine beliebige Anzahl von separaten Caches pro Benutzer. Alle Prozesse mit der gleichen Cache-ID und dem gleichen Benutzer teilen sich eine OPcache-Instanz.

stat

Die Implementierung von stat wurde überarbeitet.

  • Es wird eine Inode-Nummer geliefert, die auf dem NTFS-Datei-Index basiert.
  • Die Gerätenummer basiert nun auf der Seriennummer des Laufwerks.

Es ist zu beachten, dass beide Werte vom System abgeleitet werden und auf 64-Bit-Systemen unverändert zur Verfügung stehen. Auf 32-Bit-Systemen könnten diese Werte zum Überlauf der 32-Bit-Integer von PHP führen und sind daher falsch.

libsqlite3

libsqlite3 wird nicht mehr statisch in php_sqlite3.dll und php_pdo_sqlite.dll kompiliert, sondern steht stattdessen als libsqlite3.dll zur Verfügung. Siehe dazu die Installationsanweisungen für SQLite3 und PDO_SQLITE.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 7.2.x auf PHP 7.3.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features
  • Sonstige Änderungen
  • Windows-Unterstützung

Diese neue Minor-Version bringt eine Reihe von neuen Features und einige wenige Inkompatibilitäten, die vor der Umstellung der PHP-Versionen in der Produktivumgebung getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.0.x, 7.1.x und 7.2.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

PHP-Kern

Flexiblere Heredoc- und Nowdoc-Syntax

Auf den schließenden Bezeichner für doc-Zeichenketten muss kein Semikolon oder Zeilenumbruch mehr folgen. Außerdem darf der schließende Bezeichner eingerückt sein; in diesem Fall wird die Einrückung aus allen Zeilen der doc-Zeichenkette entfernt.

Die Destrukturierung (Zerlegung) von Arrays unterstützt Referenzzuweisungen

Die Destrukturierung von Arrays unterstützt nun mithilfe der Syntax [&$a, [$b, &$c]] = $d Referenzzuweisungen. Dies wird auch bei list() unterstützt.

Der Operator instanceof akzeptiert Literale

Der Operator instanceof akzeptiert nun ein Literal als ersten Operanden. In diesem Fall gibt das Ergebnis immer false zurück.

CompileError-Exception anstelle von Kompilierungsfehlern

Es wurde eine neue CompileError-Exception hinzugefügt, von der ParseError erbt. Eine kleine Anzahl von Kompilierungsfehlern löst nun eine CompileError-Exception aus, anstatt einen fatalen Fehler zu erzeugen. Derzeit betrifft dies nur Kompilierungsfehler, die von token_get_all() im Modus TOKEN_PARSE ausgelöst werden können, aber in Zukunft könnten weitere Fehler in diese Exception konvertiert werden.

Komma am Ende von Aufrufen erlaubt

Am Ende von Funktions- und Methodenaufrufen sind nun Kommas erlaubt.

Unterstützung für Argon2id

Mit der Konfigurationsoption --with-password-argon2[=dir] unterstützen die Funktionen password_hash(), password_verify(), password_get_info() und password_needs_rehash() nun Argon2i- und Argon2id-Hashes. Passwörter können gehasht und mit der Konstante PASSWORD_ARGON2ID verifiziert werden. Um die Unterstützung für Argon2i und Argon2id in den password_*()-Funktionen nutzen zu können, muss PHP gegen die libargon2-Referenzbibliothek = 20161029 gelinkt sein.

FastCGI-Prozessmanager (FPM)

Es wurden neue Optionen zur Anpassung der FPM-Protokollierung hinzugefügt:

log_limit
Diese globale Option wird verwendet, um die maximale Textlänge für die Protokollierung festzulegen, sodass es möglich ist, mehr als 1024 Zeichen ohne Zeilenumbrüche zu protokollieren. Dadurch werden auch verschiedene Probleme mit Zeilenumbrüchen behoben.
log_buffering
Diese globale Option ermöglicht eine experimentelle Protokollierung ohne zusätzliche Pufferung.
decorate_workers_output
Wenn catch_workers_output aktiviert ist, kann diese Pool-Option verwendet werden, um die Dekoration der Worker-Ausgabe zu deaktivieren.

BCMath-Funktionen

Die Funktion bcscale() kann nun auch als "Getter" verwendet werden, um die aktuell verwendete Genauigkeit abzurufen.

Lightweight Directory Access Protocol (LDAP)

Die LDAP-Abfragefunktionen und die Funktion ldap_parse_result() unterstützen nun sämtliche Steuerelemente von LDAP:

  • Um Steuerbefehle an den Server senden zu können, wurde den Funktionen
ldap_add(), ldap_mod_replace(),
ldap_mod_add(), ldap_mod_del(),
ldap_rename(), ldap_compare(),
ldap_delete(), ldap_modify_batch(),
ldap_search(), ldap_list() und
ldap_read() der Parameter
$controls hinzugefügt.
  • Um Steuerbefehle vom Server abrufen zu können wurde der Funktion ldap_parse_result() der Parameter $controls hinzugefügt.
  • In den Funktionen ldap_get_option() und ldap_set_option() wurde die Unterstützung für LDAP_OPT_SERVER_CONTROLS und LDAP_OPT_CLIENT_CONTROLS korrigiert.

Multibyte-Zeichenketten-Funktionen

Vollständige Unterstützung für Case-Mapping und Case-Folding

Die Unterstützung für die vollständige Umwandlung und den Vergleich von Groß- und Kleinschreibung wurde hinzugefügt. Im Gegensatz zur einfachen Umwandlung der Groß-/Kleinschreibung kann die vollständige Umwandlung die Länge der Zeichenkette ändern. Zum Beispiel:

<?php
mb_strtoupper("Straße");
// Ergibt in PHP 7.2 STRAßE
// Ergibt in PHP 7.3 STRASSE
?>
In mb_convert_case() stehen verschiedene Modi für die Umwandlung und zum Vergleich von Groß- und Kleinschreibung zur Verfügung:
  • MB_CASE_LOWER (wird verwendet von mb_strtolower())
  • MB_CASE_UPPER (wird verwendet von mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (wird bei Operationen verwendet, die Groß- und Kleinschreibung nicht berücksichtigen)
Es wird nur uneingeschränktes und sprachunabhängiges vollständiges Case-Mapping durchgeführt.

Operationen, die Groß-/Kleinschreibung nicht berücksichtigen, verwenden Case-Folding

Bei Operationen mit Zeichenketten, die die Groß-/Kleinschreibung nicht berücksichtigen, wird nun Case-Folding anstelle von Case-Mapping verwendet. Das bedeutet, dass mehr Zeichen als gleich (ohne Berücksichtigung der Groß-/Kleinschreibung) angesehen werden.

MB_CASE_TITLE führt eine Title-Case-Umwandlung durch

mb_convert_case() führt in Verbindung mit MB_CASE_TITLE nun eine Title-Case-Umwandlung durch, die auf den von Cased und CaseIgnorable abgeleiteten Unicode-Eigenschaften basiert. Diese Änderung verbessert insbesondere auch die Behandlung von Anführungszeichen und Apostrophen.

Unterstützung für Unicode 11

Die Datentabellen für Multibyte-Zeichenketten wurden aktualisiert, um Unicode 11 zu unterstützen.

Unterstützung für lange Zeichenketten

Die Funktionen für Multibyte-Zeichenketten unterstützen nun auch Zeichenketten, die größer als 2GB sind.

Verbesserung der Leistung

Die Leistung der Erweiterung Multibyte-Zeichenketten wurde in allen Bereichen erheblich verbessert. Die größten Verbesserungen betreffen die Funktionen zur Umwandlung der Groß-/Kleinschreibung.

Unterstützung für benannte Übereinstimmungen

Die mb_ereg_*-Funktionen unterstützen nun benannte Übereinstimmungen. Funktionen, die wie mb_ereg() nach Übereinstimmungen suchen, geben nun ähnlich wie die Funktionen bei PCRE benannte Übereinstimmungen zurück, indem sie sowohl ihre Gruppennummern als auch ihre Namen verwenden:

<?php
mb_ereg('(?<word>\w+)', '?', $matches);
// => [0 => "?", 1 => "?", "word" => "?"];
?>
Außerdem unterstützt mb_ereg_replace() nun die Notationen \k<> und \k'', um benannte Übereinstimmungen in der Ersetzungszeichenkette zu referenzieren:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> und \k'' können auch für numerische Verweise verwendet werden, was auch mit Gruppennummern funktioniert, die größer als 9 sind.

Readline

Bei der Funktion readline_info() wurde die Unterstützung für die Optionen completion_append_character und completion_suppress_append hinzugefügt. Diese Optionen sind nur verfügbar, wenn PHP gegen libreadline (statt libedit) gelinkt ist.

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

?>


Neue Funktionen

PHP-Kern

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI Process Manager

  • fpm_get_status()

Datum und Uhrzeit

  • DateTime::createFromImmutable()

GNU Multiple Precision

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

Internationalization Functions

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


Neue globale Konstanten

PHP-Kern

  • PASSWORD_ARGON2ID

Client URL-Bibliothek

  • 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 (ab PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (ab 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 (ab PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Daten-Filterung

  • FILTER_SANITIZE_ADD_SLASHES

JavaScript Object Notation

  • JSON_THROW_ON_ERROR

Lightweight Directory Access Protocol

  • LDAP_CONTROL_ASSERT
  • LDAP_CONTROL_MANAGEDSAIT
  • LDAP_CONTROL_PROXY_AUTHZ
  • LDAP_CONTROL_SUBENTRIES
  • LDAP_CONTROL_VALUESRETURNFILTER
  • LDAP_CONTROL_PRE_READ
  • LDAP_CONTROL_POST_READ
  • LDAP_CONTROL_SORTREQUEST
  • LDAP_CONTROL_SORTRESPONSE
  • LDAP_CONTROL_PAGEDRESULTS
  • LDAP_CONTROL_AUTHZID_REQUEST
  • LDAP_CONTROL_AUTHZID_RESPONSE
  • LDAP_CONTROL_SYNC
  • LDAP_CONTROL_SYNC_STATE
  • LDAP_CONTROL_SYNC_DONE
  • LDAP_CONTROL_DONTUSECOPY
  • LDAP_CONTROL_PASSWORDPOLICYREQUEST
  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE
  • LDAP_CONTROL_X_INCREMENTAL_VALUES
  • LDAP_CONTROL_X_DOMAIN_SCOPE
  • LDAP_CONTROL_X_PERMISSIVE_MODIFY
  • LDAP_CONTROL_X_SEARCH_OPTIONS
  • LDAP_CONTROL_X_TREE_DELETE
  • LDAP_CONTROL_X_EXTENDED_DN
  • LDAP_CONTROL_VLVREQUEST
  • LDAP_CONTROL_VLVRESPONSE

Multibyte-Strings

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


Nicht abwärtskompatible Änderungen

PHP-Kern

Interpretation des schließenden Heredoc/Nowdoc-Bezeichners

Durch die Einführung der flexiblen Heredoc/Nowdoc-Syntax können doc-Zeichenketten, die den schließenden Bezeichner in ihrem Körper enthalten, zu Syntaxfehlern oder einer veränderten Interpretation führen. Zum Beispiel in:

<?php
$str = <<<FOO
abcdefg
 FOO
FOO;
?>
hatte das eingerückte FOO bisher keine besondere Bedeutung. Nun wird es als Ende der Heredoc-Zeichenkette interpretiert und das folgende FOO; führt zu einem Syntaxfehler. Dieses Problem kann immer gelöst werden, indem ein schließender Bezeichner gewählt wird, der nicht im Inhalt der Zeichenkette vorkommt.

Warnung bei continue in switch-Anweisung

Eine continue-Anweisung, die in einer switch-Kontrollstruktur verwendet wird, erzeugt nun eine Warnung. In PHP sind solche continue-Anweisungen gleichbedeutend mit break, während sie sich in anderen Sprachen wie continue 2 verhalten.

<?php
while ($foo) {
switch ($bar) {
case "baz":
continue;
// Warning: "continue" targeting switch is equivalent to
// "break". Did you mean to use "continue 2"?
}
}
?>

Strikte Interpretation von ganzzahligen Zeichenketten-Schlüsseln bei ArrayAccess

Ein Array-Zugriff vom Typ $obj["123"], worin $obj ArrayAccess implementiert und "123" ein ganzzahliges Literal vom Typ string ist, führt nicht mehr zu einer impliziten Umwandlung in eine Ganzzahl, d. h., anstelle von $obj->offsetGet(123) wird nun $obj->offsetGet("123") aufgerufen. Dies entspricht dem bestehenden Verhalten für nicht-literale Werte. Das Verhalten von Arrays wird davon in keiner Weise beeinflusst; sie wandeln ganzzahlige Zeichenketten-Schlüssel weiterhin implizit in Ganzzahlen um.

Statische Eigenschaften werden nicht mehr durch Referenzzuweisung getrennt

In PHP werden statische Eigenschaften von vererbenden Klassen gemeinsam genutzt, es sei denn, die statische Eigenschaft wird in einer Kindklasse explizit überschrieben. Allerdings war es aufgrund eines Implementierungs-Artefakts möglich, die statischen Eigenschaften durch Zuweisung einer Referenz zu trennen. Dieses Schlupfloch wurde nun behoben.

<?php
class Test {
public static $x = 0;
}
class Test2 extends Test { }

Test2::$x = &$x;
$x = 1;

var_dump(Test::$x, Test2::$x);
// Vorher: int(0), int(1)
// Nun: int(1), int(1)
?>

Referenzen, die von Array- und Eigenschafts-Zugriffen zurückgegeben werden, werden sofort aufgelöst

Eine Referenz, die von einem Array- oder Eigenschafts-Zugriff zurückgegeben wird, wird nun im Zuge des Zugriffs aufgelöst. Das bedeutet, dass es nicht mehr möglich ist, die Referenz zwischen dem Zugriff und der Verwendung des Wertes, auf den zugegriffen wurde, zu verändern:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Vorher: int(4), Nun: int(3)
?>
Dadurch wird das Verhalten von Referenzen und Nicht-Referenzen konsistent. Es ist zu beachten, dass das Lesen und Schreiben eines Wertes innerhalb eines einzelnen Ausdrucks weiterhin undefiniertes Verhalten bleibt und sich in der Zukunft wieder ändern kann.

Entpacken von Parametern bei Traversables mit nicht-ganzzahligen Schlüsseln wird nicht mehr unterstützt

Das Entpacken von Parametern funktioniert bei Traversables mit nicht-ganzzahligen Schlüsseln nicht mehr. Der folgende Code funktionierte in PHP 5.6-7.2 unbeabsichtigt.

<?php
function foo(...$args) {
var_dump($args);
}
function gen() {
yield 1.23 => 123;
}
foo(...gen());
?>

Verschiedenes

Das Hilfsprogramm ext_skel wurde komplett überarbeitet; neue Optionen wurden hinzugefügt und einige alte Optionen entfernt. Es ist nun in PHP geschrieben und hat keine externen Abhängigkeiten.

Die Unterstützung für BeOS wurde eingestellt.

Exceptions, die im Modus EH_THROW durch die automatische Umwandlung von Warnungen in Exceptions ausgelöst werden (z. B. einige DateTime-Exceptions), füllen den Bereich von error_get_last() nicht mehr mit Daten. Damit funktionieren sie nun genauso wie manuell ausgelöste Exceptions.

TypeError meldet nun falsche Typen als int und bool anstelle von integer bzw. boolean.

Undefinierte Variablen, die an compact() übergeben werden, werden nun als Hinweis gemeldet.

Die Funktion getimagesize() und verwandte Funktionen melden nun den Mime-Typ von BMP-Bildern als image/bmp anstelle von image/x-ms-bmp, da ersterer bei der IANA registriert ist (siehe » RFC 7903).

Die Funktion stream_socket_get_name() gibt nun IPv6-Adressen zurück, die in Klammern eingeschlossen sind. Zum Beispiel wird nun "[::1]:1337" anstelle von "::1:1337" zurückgegeben.

BCMath mathematische Berechnungen mit beliebiger Genauigkeit

Alle Warnungen, die von BCMath-Funktionen ausgelöst werden, verwenden nun die Fehlerbehandlung von PHP. Zuvor wurden einige Warnungen direkt nach stderr geschrieben.

Die Funktionen bcmul() und bcpow() geben nun Zahlen mit der geforderten Genauigkeit zurück. Zuvor wurden in den zurückgegebenen Zahlen unter Umständen die Dezimalnullen am Ende weggelassen.

IMAP, POP3 und NNTP

Anmeldungen über rsh/ssh sind standardmäßig deaktiviert. Um dies zu ändern, muss imap.enable_insecure_rsh verwendet werden. Es ist zu beachten, dass die IMAP-Bibliothek die Namen der Postfächer nicht filtert, bevor sie an den rsh/ssh-Befehl übergeben werden. Daher sollten bei aktiviertem rsh/ssh keine nicht vertrauenswürdigen Daten an diesen Befehl übergeben werden.

Multibyte-Zeichenketten

Aufgrund der hinzugefügten Unterstützung für benannte Teilsuchmuster verhalten sich mb_ereg_*()-Suchmuster, die diese verwenden, anders. Insbesondere werden benannte Teilsuchmuster Teil der Treffer sein und mb_ereg_replace() wird die zusätzliche Syntax auswerten. Siehe Benannte Teilsuchmuster für weitere Informationen.

Verbesserte MySQL-Erweiterung (MySQLi)

Vorbereitete Anweisungen (Prepared Statements) geben die Sekundenbruchteile bei DATETIME-, TIME- und TIMESTAMP-Spalten mit Dezimalspezifizierer (z. B. TIMESTAMP(6) bei Verwendung von Mikrosekunden) nun korrekt an. In früheren Versionen wurden sie in den zurückgegebenen Werten einfach weggelassen.

MySQL-Funktionen (PDO_MYSQL)

Vorbereitete Anweisungen geben die Sekundenbruchteile bei DATETIME-, TIME- und TIMESTAMP-Spalten mit Dezimalspezifizierer (z. B. TIMESTAMP(6) bei Verwendung von Mikrosekunden) nun korrekt an. In früheren Versionen wurden sie in den zurückgegebenen Werten einfach weggelassen. Zu beachten ist, dass dies nur die PDO_MYSQL-Anweisungen betrifft, bei denen die Emulation vorbereiteter Anweisungen deaktiviert ist (z. B. bei Verwendung der nativen Prepair-Funktionalität von MySQL). Anweisungen, die Verbindungen mit PDO::ATTR_EMULATE_PREPARES=true verwenden (die Standardeinstellung), waren von dem behobenen Fehler nicht betroffen und erhielten bereits korrekte Sekundenbruchteile von der Engine.

Reflection

Beim Exportieren von Reflection-Objekten in Zeichenketten werden nun int und bool anstelle von integer bzw. boolean verwendet.

Standard-PHP-Bibliothek (SPL)

Wenn ein SPL-Autoloader eine Exception auslöst, werden die folgenden Autoloader nicht mehr ausgeführt. Zuvor wurden alle Autoloader ausgeführt und die Exceptions wurden verkettet.

SimpleXML

Wenn eine mathematische Operation ein SimpleXML-Objekt enthält, wird der Text nun als int oder float behandelt, je nachdem, was besser geeignet ist. Zuvor wurden Werte grundsätzlich als ints behandelt.

Eingehende Cookies

Seit PHP 7.3.23 werden die Namen eingehender Cookies aus Sicherheitsgründen nicht mehr URL-dekodiert.

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.


Veraltete Features

PHP-Kern

Konstanten die von Groß-/Kleinschreibung unabhängig sind

Die Deklaration von Konstanten, die von Groß-/Kleinschreibung unabhängig sind, wird nun als veraltet angesehen. Die Übergabe von true als drittes Argument an define() ruft nun einen entsprechende Veraltet-Warnung hervor. Die Verwendung einer Konstante die unabhängig von Groß-/Kleinschreibung ist in einer anderen Schreibweise als bei der Deklaration ist nun ebenfalls veraltet.

assert() in Namespaces

Die Deklaration einer Funktion namens assert() innerhalb eines Namespaces ist veraltet. Die Funktion assert() wird durch die Engine besonders behandelt, was zu inkonsistentem Verhalten führen kann, wenn eine gleich benannte Funktion in einem Namespace definiert wird.

Durchsuchen von Zeichenketten nach einer Nicht-Zeichenkette

Die Übergabe von Suchbegriffen, die keine Strings sind, an Zeichenketten-Suchfunktionen ist veraltet. Zukünftig wird der Suchbegriff statt als ASCII-Codepunkt als Zeichenkette interpretiert. Je nach gewünschtem Verhalten sollte der Suchbegriff entweder direkt in einen String gecastet oder die Funktion chr() direkt aufgerufen werden. Betroffen sind folgende Funktionen:

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags-Streams

Die Funktion fgetss() und der Stream-Filter string.strip_tags sind nun veraltet. Davon betroffen ist auch die Methode SplFileObject::fgetss() und die Funktion gzgetss().

Daten-Filterung

Die explizite Verwendung der Konstanten FILTER_FLAG_SCHEME_REQUIRED und FILTER_FLAG_HOST_REQUIRED ist jetzt veraltet. Beide sind bereits implizit in FILTER_VALIDATE_URL enthalten.

Bildbearbeitung und GD

image2wbmp() ist nun veraltet.

Funktionen zur Internationalisierung

Die Verwendung der Form Normalizer::NONE ruft nun eine Veraltet-Warnung hervor, wenn PHP gegen ICU = 56 gelinkt ist.

Multibyte-Strings

Die folgenden umdokumentierten Aliase mbereg_*() sind nun veraltet. Es sollten stattdessen die zugehörigen Varianten von mb_ereg_*() verwendet werden.

  • mbregex_encoding()
  • mbereg()
  • mberegi()
  • mbereg_replace()
  • mberegi_replace()
  • mbsplit()
  • mbereg_match()
  • mbereg_search()
  • mbereg_search_pos()
  • mbereg_search_regs()
  • mbereg_search_init()
  • mbereg_search_getregs()
  • mbereg_search_getpos()
  • mbereg_search_setpos()

ODBC und DB2-Funktionen (PDO_ODBC)

Die Ini-Einstellung pdo_odbc.db2_instance_name ist nun formell als veraltet markiert. Die Dokumentation benannte dies bereits seit PHP 5.1.1 als veraltet.

User Contributed Notes

There are no user contributed notes for this page.


Sonstige Änderungen

PHP-Kern

Set(raw)cookie akzeptiert den Parameter $option

Die Funktionen setcookie() und setrawcookie() unterstützen nun auch die folgende Signatur:

setcookie(string $name, string $value = "", array $options = []): bool
wobei $options ein assoziatives Array ist, das die folgenden Schlüssel haben kann: "expires", "path", "domain", "secure", "httponly" und "samesite".

Neue INI-Direktiven für Syslog

Die folgenden INI-Direktiven wurden hinzugefügt, um die Protokollierung anzupassen, wenn error_log auf syslog gesetzt ist:

syslog.facility
Gibt an, welche Art von Programm die Nachricht protokolliert.
syslog.filter
Gibt den Filtertyp zum Filtern der protokollierten Nachrichten an. Die unterstützten Filtertypen sind all, no-ctrl und ascii. Seit PHP 7.3.8 steht außerdem raw zur Verfügung und stellt das Verhalten von syslog aus früheren PHP-Versionen wieder her. Dieser Filter wirkt sich auch auf Aufrufe von syslog() aus.
syslog.ident
Gibt die ident-Zeichenkette an, die jeder Meldung vorangestellt wird.

Garbage-Collection

Die zyklische GC wurde verbessert, was zu erheblichen Leistungsverbesserungen führen kann.

Verschiedenes

Die Funktion var_export() exportiert stdClass-Objekte nun als Array, das in ein Objekt umgewandelt wird ((object) array( ... )), anstatt die nicht existierende Methode stdClass::__setState() zu verwenden.

Die Funktion debug_zval_dump() wurde geändert, um rekursive Arrays und Objekte auf die gleiche Weise anzuzeigen wie var_dump(). Damit werden sie nun nicht mehr doppelt angezeigt.

Die Funktionen array_push() und array_unshift() können nun auch mit einem einzigen Parameter aufgerufen werden. Dies ist besonders nützlich in Verbindung mit dem Spread-Operator (Zerlegungsoperator).

Interaktiver PHP-Debugger

Die nicht verwendeten Konstanten PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO und PHPDBG_FUNC wurden entfernt.

FastCGI-Prozessmanager (FPM)

Die Funktion getallheaders() ist nun ebenfalls verfügbar.

Client-URL-Bibliothek (cURL)

libcurl = 7.15.5 ist nun erforderlich.

Datenfilterung

Der Filter FILTER_VALIDATE_FLOAT unterstützt nun auch die Option thousand, die die erlaubten Tausendertrennzeichen definiert. Die Voreinstellung ("',.") ist vollständig abwärtskompatibel mit früheren PHP-Versionen.

Der Filter FILTER_SANITIZE_ADD_SLASHES wurde als Alias des magic_quotes-Filters (FILTER_SANITIZE_MAGIC_QUOTES) hinzugefügt. Der magic_quotes-Filter wird voraussichtlich in zukünftigen PHP-Versionen entfernt.

FTP

Der Standard-Übertragungsmodus ist nun binary.

Funktionen für die Internationalisierung

Die Konstante Normalizer::NONE ist veraltet, wenn PHP mit einer ICU-Version = 56 kompiliert wurde.

Bei der Methode Normalizer::normalize() wurde die Konstante Normalizer::FORM_KC_CF als Parameter für die NFKC_Casefold-Normalisierung hinzugefügt; sie ist verfügbar mit ICU = 56.

JavaScript Object Notation (JSON)

Das neue Flag JSON_THROW_ON_ERROR wurde hinzugefügt, das in den Funktionen json_decode() und json_encode() verwendet werden kann. Es bewirkt, dass diese Funktionen bei einem Fehler die neue JsonException auslösen, anstatt den globalen Fehlerstatus zu setzen, der mit json_last_error() und json_last_error_msg() abgerufen wird. JSON_PARTIAL_OUTPUT_ON_ERROR hat Vorrang vor JSON_THROW_ON_ERROR.

Multibyte-Zeichenketten

Die Konfigurationsoption --with-libmbfl ist nicht mehr verfügbar.

ODBC (Unified)

Die Unterstützung für ODBCRouter und Birdstep einschließlich der INI-Direktive birdstep.max_links wurde entfernt.

OPcache

Die INI-Direktive opcache.inherited_hack wurde entfernt. Der Wert wurde bereits seit PHP 5.3.0 ignoriert.

OpenSSL

Die SSL-Stream-Optionen min_proto_version und max_proto_version sowie die zugehörigen Konstanten für mögliche TLS-Protokollwerte wurden hinzugefügt.

Reguläre Ausdrücke (Perl-kompatibel)

Die Erweiterung PCRE wurde auf PCRE2 aktualisiert, was zu kleineren Änderungen im Verhalten führen kann (zum Beispiel werden Zeichenbereiche in Klassen nun strenger interpretiert) und die bestehende Syntax für reguläre Ausdrücke erweitert.

Die Funktion preg_quote() maskiert nun auch das '#'-Zeichen.

Microsoft SQL Server und Sybase-Funktionen (PDO_DBLIB)

Die Eigenschaft PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS wurde hinzugefügt, um leere Datensätze automatisch überspringen zu können.

Die Eigenschaft PDO::DBLIB_ATTR_TDS_VERSION, die die TDS-Version angibt, wurde hinzugefügt.

DATETIME2-Spalten werden nun genauso behandelt wie DATETIME-Spalten.

SQLite-Funktionen (PDO_SQLITE)

SQLite3-Datenbanken können nun im Nur-Lese-Modus geöffnet werden, indem die neue Eigenschaft PDO::SQLITE_ATTR_OPEN_FLAGS auf PDO::SQLITE_OPEN_READONLY gesetzt wird.

Handhabung von Sessions

Die Funktion session_set_cookie_params() unterstützt nun auch die folgende Signatur:

session_set_cookie_params(array $options): bool
wobei $options ein assoziatives Array ist, das folgende Schlüssel haben kann: "lifetime", "path", "domain", "secure", "httponly" und "samesite". Dementsprechend enthält der Rückgabewert der Funktion session_get_cookie_params() nun auch ein Element mit dem Schlüssel "samesite". Außerdem wurde die neue INI-Option session.cookie_samesite hinzugefügt, um die Standardeinstellung der SameSite-Direktive für Cookies festzulegen. Ihr Standardwert ist "" (die leere Zeichenkette), sodass keine SameSite-Anweisung gesetzt wird. Dieser Wert kann auf "Lax" oder "Strict" gesetzt werden, wodurch die entsprechende SameSite-Richtlinie gesetzt wird.

Tidy

PHP mit » tidyp zu kompilieren, wird nun auch transparent unterstützt. Da tidyp keine API bietet, um das Veröffentlichungsdatum abzurufen, geben die Funktionen tidy_get_release() und tidy::getRelease() in diesem Fall 'unknown' zurück.

XML-Parser

Wenn die Erweiterung gegen libxml kompiliert wurde, wird der Rückgabewert des Callbacks der Funktion xml_set_external_entity_ref_handler() nicht mehr ignoriert. Zuvor wurde der Rückgabewert ignoriert und das Parsen wurde nie beendet.

Zip

Es wird davon abgeraten, gegen die mit PHP mitgelieferte libzip zu kompilieren, aber es ist dennoch möglich, indem die Option --without-libzip zur Konfiguration hinzugefügt wird.

Komprimierung mit Zlib

Für den compress.zlib-Wrapper wurde die Kontextoption zlib/level hinzugefügt, um die Einstellung der gewünschten Kompressionsstufe zu erleichtern.

User Contributed Notes

There are no user contributed notes for this page.


Windows-Unterstützung

PHP-Kern

POSIX konformere Datei-Löschung

Datei-Deskriptoren werden standardmäßig im gemeinsamen Lese-/Schreib-/Löschmodus geöffnet. Dies bildet im Grunde die POSIX Semantik ab, und erlaubt Dateien mit verwendeten Handles zu löschen. Es ist nicht 100% das gleiche, einige Plattform-Differenzen bestehen nach wie vor. Nach der Löschung ist der Dateinameneintrag blockiert, bis alle geöffneten Handles zu ihm geschlossen sind.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 7.1.x auf PHP 7.2.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features in PHP 7.2.x
  • Sonstige Änderungen

Diese neue Minor-Version bringt eine Reihe von neuen Features und einige wenige Inkompatibilitäten, die vor der Umstellung der PHP-Versionen in der Produktions-Umgebung getestet werden sollten.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.0.x und 7.1.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

Neuer Typ: object

Der neue Typ object wurde eingeführt. Er kann verwendet werden, um (kontravariant) Parameter und (kovariant) Rückgabewerte beliebiger Objekte zu typisieren.

<?php

function test(object $obj) : object
{
return new SplQueue();
}

test(new stdClass());

Erweiterung nach Name laden

Um Shared- (gemeisam genutzte) Erweiterungen zu laden, wird keine Dateierweiterung (.so unter Unix oder .dll unter Windows) mehr benötigt. Dies gilt sowohl für die Datei php.ini als auch für die Funktion dl().

Überschreiben abstrakter Methoden

Wenn eine abstrakte Klasse eine andere abstrakte Klasse erweitert, ist es nun möglich, abstrakte Methoden zu überschreiben.

<?php

abstract class A
{
abstract function test(string $s);
}
abstract class B extends A
{
// überschrieben - die Kontravarianz für die Parameter und die Kovarianz für die Rückgabe bleiben erhalten
abstract function test($s) : int;
}

Sodium ist nun eine Standarderweiterung

Die moderne kryptographische Bibliothek Sodium ist nun eine Kern-Erweiterung von PHP.

Eine vollständige Funktionsreferenz befindet sich im Kapitel Sodium.

Passwort-Hashing mit Argon2

Die Passwort-Hashing-API wurde um Argon2 erweitert. Es stehen die folgenden Konstanten zur Verfügung:

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

Erweiterte Zeichenketten-Typen für PDO

Der Zeichenketten-Typ von PDO wurde erweitert, um nationale Zeichensätze bei der Emulation vorbereiteter Anweisungen (Prepared Statements) zu unterstützen. Dafür wurden folgende Konstanten hinzugefügt:

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

Diese Konstanten können verwendet werden, indem sie durch bitweises OR mit PDO::PARAM_STR verkettet werden:

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

Zusätzliche Debugging-Informationen bei der Emulation vorbereiteter Anweisungen in PDO

Die Methode PDOStatement::debugDumpParams() wurde aktualisiert, und enthält nun auch die an die DB gesendete SQL-Anweisung, wobei die vollständige, unbearbeitete Anweisung (einschließlich der durch ihre zugehörigen Werte ersetzten Platzhalter) angezeigt wird. Dies wurde hinzugefügt, um die Fehlersuche bei emulierten vorbereiteten Anweisungen zu erleichtern (und ist daher nur verfügbar, wenn die Emulation vorbereiteter Anweisungen aktiviert ist).

Unterstützung für erweiterte Operationen in LDAP

Die Erweiterung LDAP wurde um die Unterstützung für EXOP erweitert. Dafür wurden folgende Funktionen und Konstanten hinzugefügt:

  • 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

Ergänzung der Erweiterung Sockets um Adressinformationen

Die Erweiterung Sockets bietet nun die Möglichkeit, Adressinformationen abzurufen, eine Verbindung zu ihnen herzustellen, an sie zu binden und Informationen darüber abzurufen. Dafür wurden die folgenden vier Funktionen hinzugefügt:

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Erweiterung des Parametertyps

Die Parametertypen können bei einer überschriebenen Methode und bei der Implementierung einer Schnittstelle nun weggelassen werden. Da die Parametertypen kontravariant sind, wird das Liskovsche Substitutionsprinzip (LSP) dabei nicht verletzt.

<?php

interface A
{
public function Test(array $input);
}

class B implements A
{
public function Test($input){} // Typ für $input weggelassen
}

Nachgestelltes Komma bei gruppierten Namensräumen erlaubt

Die in PHP 7.0 eingeführte Syntax für Gruppen erlaubt nun ein abschließendes Komma.

<?php

use Foo\Bar\{
Foo,
Bar,
Baz,
};

Unterstützung für proc_nice() unter Windows

Die Funktion proc_nice() wird nun auch unter Windows unterstützt.

Unterstützung der Byte-Reihenfolge in pack() und unpack()

Die Funktionen pack() und unpack() unterstützen Floats und Doubles nun sowohl im Format Little-Endian als auch im Format Big-Endian.

Verbesserungen bei der Erweiterung EXIF

Die Erweiterung EXIF wurde aktualisiert und unterstützt nun mehr Formate. Das bedeutet, dass deren formatspezifische Tags bei der Analyse von Bildern mit der Funktion exif_read_data() nun korrekt übersetzt werden. Die folgenden neuen Formate werden nun unterstützt:

  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

Die EXIF-Funktionen exif_read_data() und exif_thumbnail() unterstützen nun die Übergabe eines Streams als ihren ersten Parameter.

Neue Features in PCRE

  • Der Modifikator J wurde hnzugefügt, um PCRE_DUPNAMES setzen zu können.

SQLite3 ermöglicht das Schreiben von BLOBs

Mit der Methode SQLite3::openBlob() können nun BLOB-Felder im schreibenden Modus geöffnet werden. Zuvor wurde nur der lesende Modus unterstützt.

Oracle OCI8 Transparent Application Failover Callbacks

Die Unterstützung für Oracle Database Transparent Application Failover (TAF) Callbacks wurde hinzugefügt. TAF ermöglicht es PHP-OCI8-Anwendungen, die Verbindung zu einer vorkonfigurierten Datenbank automatisch wiederherzustellen, wenn sie unterbrochen wird. Mit TAF-Callbacks kann die Wiederherstellung der Verbindung während des Failovers von der PHP-Anwendung aus überwacht und gesteuert werden.

Verbesserungen bei der Erweiterung ZIP

Die Unterstützung für das Lesen und Schreiben verschlüsselter Archive wurde hinzugefügt (erfordert libzip 1.2.0).

Die Klasse ZipArchive implementiert nun die Schnittstelle Countable.

Der zip://-Stream akzeptiert nun die Kontextoption 'password'.

User Contributed Notes

antonfedonyuk at gmail dot com 21-Apr-2021 12:27
Note: "omitted" = "removed":
<?php
declare(strict_types=1);

interface ITest
{
    public function run(array $input);
}

class Test implements ITest
{
    public function run($input) {
       return $input;
   }
}

echo (new Test())->run('foo'); // display foo, no error
?>
info at ensostudio dot ru 11-Sep-2020 07:28
Note: you cant change parameter type for abstract method defined in interface.
<?php
abstract class AbstractAssocArray imlements ArrayAccess
{
    abstract public function offsetSet($offset, $value): void;
    ...
}
abstract class AbstractAssocArray2 extends AbstractAssocArray
{
    abstract public function offsetSet(string $offset, $value): void;
}
class AssocArray extends AbstractAssocArray2
{
    public function offsetSet(string $offset, $value): void
    {
         $this->{$offset} = $value;
    }
}
?>
It's throw fatal error: Declaration of AbstractAssocArray::offsetSet(string $offset, $value): void must be compatible with AbstractAssocArrayAccess::offsetSet($offset, $value).


Neue Funktionen

PHP-Kern

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


Neue globale Konstanten

PHP Core

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

Dateiinformation

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


Nicht abwärtskompatible Änderungen

number_format() gibt keine negativen Nullen zurück

In früheren Versionen konnte die Funktion number_format() -0 zurückgeben. Dies ist zwar für Gleitkommazahlen nach dem Standard IEEE-754 durchaus zulässig, aber in Bezug auf die Formatierung der Zahlen in einer für den Menschen lesbaren Form war diese Eigenart nicht wünschenswert.

<?php

var_dump(number_format(-0.01)); // gibt nun string(1) "0" anstelle von string(2) "-0" aus

Behandlung numerischer Schlüssel bei Umwandlungen zwischen Objekten und Arrays

Numerische Schlüssel werden nun besser behandelt, wenn Arrays in Objekte und Objekte in Arrays umgewandelt werden. Dies gilt nicht nur für explizite Umwandlungen, sondern auch für die Verwendung von settype().

Das bedeutet, dass auf die (zeichenkettenartigen) Integer-Schlüssel eines Arrays, das in ein Objekt umgewandelt wird, nun zugegriffen werden kann:

<?php

// Array zu Objekt
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
$obj,
$obj->{'0'}, // nun verfügbar
$obj->{0} // nun verfügbar
);

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(stdClass)#1 (1) {
  ["0"]=>    // nun ein Zeichenketten-Schlüssel anstelle eines Integer-Schlüssels
  int(1)
}
int(1)
int(1)

Genauso kann nun auf die (zeichenkettenartigen) Integer-Schlüssel eines Objekts, das in ein Array umgewandelt wird, zugegriffen werden:

<?php

// object to array
$obj = new class {
public function __construct()
{
$this->{0} = 1;
}
};
$arr = (array)$obj;
var_dump(
$arr,
$arr[0], // nun verfügbar
$arr['0'] // nun verfügbar
);

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(1) {
  [0]=>    // nun ein Integer-Schlüssel anstelle eines Zeichenketten-Schlüssels
  int(1)
}
int(1)
int(1)

Keine Übergabe von null an get_class()

Bisher wurde bei der Übergabe von null an die Funktion get_class() der Name der umschließenden Klasse ausgegeben. Dieses Verhalten wurde nun entfernt und es wird stattdessen ein Fehler der Stufe E_WARNING ausgegeben. Um das beschriebene Verhalten wiederherzustellen, sollte der Parameter einfach weggelassen werden.

Warnung beim Zählen nicht zählbarer Typen

Wenn versucht wird, nicht zählbare Typen mittels count() zu zählen, wird nun ein Fehler der Stufe E_WARNING ausgegeben (dies gilt auch für die Alias-Funktion sizeof()).

<?php

var_dump(
count(null), // NULL ist nicht zählbar
count(1), // Integer sind nicht zählbar
count('abc'), // Zeichenketten sind nicht zählbar
count(new stdClass), // Objeke, die die Countable-Schnittstelle nicht implementieren, sind nicht zählbar
count([1,2]) // Arrays sind zählbar
);

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d
int(0)
int(1)
int(1)
int(1)
int(2)

ext/hash verwendet Objekte statt Ressourcen

Als Teil der langfristigen Umstellung weg von Ressourcen wurde die Erweiterung Hash dahingehend überarbeitet, dass nun Objekte anstelle von Ressourcen verwendet werden. Die Änderung sollte für PHP-Entwickler problemlos vonstatten gehen, mit Ausnahme der Fälle, in denen Überprüfungen mit der Funktion is_resource() durchgeführt werden (diese müssen auf is_object() umgestellt werden).

Verbesserung der SSL/TLS-Standardeinstellungen

Folgendes wurde an den Standardeinstellungen geändert:

  • tls:// ist nun standardmäßig auf TLSv1.0 oder TLSv1.1 oder TLSv1.2 eingestellt
  • ssl:// ist nun ein Alias für tls://
  • Die STREAM_CRYPTO_METHOD_TLS_*-Konstanten sind nun standardmäßig auf TLSv1.0 oder TLSv1.1 + TLSv1.2 eingestellt, statt nur auf TLSv1.0

Rückgabewert von gettype() bei geschlossenen Ressourcen

Bisher gab gettype() bei einer geschlossenen Ressource die Zeichenkette "unknown type" zurück. Nun wird die Zeichenkette "resource (closed)" zurückgegeben.

is_object() und __PHP_Incomplete_Class

Bisher gab die Funktion is_object() bei der Klasse __PHP_Incomplete_Class false zurück. Nun gibt sie true zurück.

Erhöhung der Fehlerstufe bei undefinierten Konstanten

Unvollständig definierte Referenzen auf undefinierte Konstanten erzeugen nun einen Fehler der Stufe E_WARNING (statt E_NOTICE). In der nächsten Hauptversion von PHP werden sie Error-Exceptions auslösen.

Windows-Unterstützung

Die derzeit niedrigsten offiziell unterstützten Windows-Version sind Windows 7/Server 2008 R2.

Überprüfung der Standard-Eigenschaftswerte von Traits

Bei Kompatibilitätsprüfungen von Standard-Eigenschaftswerten von Traits werden nun keine Typumwandlungen mehr durchgeführt.

object als Klassenname

Die Bezeichnung object war in PHP 7.0 bisher weich reserviert. Nun ist sie hart reserviert, d. h., sie kann nicht mehr als Name für Klassen, Traits oder Schnittstellen verwendet werden.

NetWare-Unterstützung

Die Unterstützung für NetWare wurde entfernt.

array_unique() mit SORT_STRING

Während array_unique() mit SORT_STRING früher das Array kopiert und nicht eindeutige Elemente entfernt hat (ohne das Array anschließend zu packen), wird nun ein neues Array erstellt, das aus den eindeutigen Elementen besteht. Dies kann zu unterschiedlichen numerischen Indizes führen.

Änderungen an bcmod() bei Gleitkommazahlen

Die Funktion bcmod() reduziert Gleitkommazahlen nicht mehr auf Ganzzahlen. Daher entspricht ihr Verhalten nun der Funktion fmod() und nicht mehr dem Operator %. Zum Beispiel liefert bcmod('4', '3.5') nun 0.5 anstelle von 1.

Hashing-Funktionen und nicht-kryptographische Hashes

Die Funktionen hash_hmac(),
hash_hmac_file(), hash_pbkdf2() und
hash_init() (mit HASH_HMAC)
akzeptieren keine nicht-kryptographischen Hashes mehr.

Funktionsoptionen für json_decode()

Wenn bei der Funktion json_decode() der zweite Parameter (assoc) null ist, wird nun die Funktionsoption JSON_OBJECT_AS_ARRAY verwendet. Zuvor wurde JSON_OBJECT_AS_ARRAY immer ignoriert.

Die Rückgabewerte von rand() und mt_rand()

Die Sequenzen, die von den Funktionen rand() und mt_rand() für einen bestimmten Seed erzeugt werden, können sich auf 64-Bit-Systemen von den in PHP 7.1 erzeugten unterscheiden (aufgrund eines behobenen Modulo-Bias-Fehlers in der Implementierung).

INI-Einstellung sql.safe_mode entfernt

Die INI-Einstellung sql.safe_mode wurde entfernt.

Änderungen an date_parse() und date_parse_from_format()

Das Element zone des Arrays, das von den Funktionen date_parse() und date_parse_from_format() zurückgegeben wird, zeigt nun Sekunden anstelle von Minuten, und sein Vorzeichen wurde umgedreht. So wird zum Beispiel -120 nun zu 7200.

Eingehende Cookies

Seit PHP 7.2.34 werden die Namen eingehender Cookies aus Sicherheitsgründen nicht mehr URL-dekodiert.

User Contributed Notes

There are no user contributed notes for this page.


Veraltete Features in PHP 7.2.x

Zeichenketten ohne Anführungszeichen

Eine Zeichenkette, die nicht in Anführungszeichen steht, wird nur dann als Zeichenkette behandelt, wenn es keine globale Konstante mit diesem Namen gibt. Dieser Fall erzeugte bisher einen Fehler der Stufe E_NOTICE und erzeugt nun stattdessen einen Fehler der Stufe E_WARNING. In der nächsten PHP-Hauptversion wird dann eine Error-Exception ausgelöst.

<?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() und jpeg2wbmp()

Bei der Erweiterung GD sind die Funktionen png2wbmp() und jpeg2wbmp() nun veraltet und werden in der nächsten PHP-Hauptversion entfernt.

Die Variante INTL_IDNA_VARIANT_2003

In der Erweiterung Intl ist die Variante INTL_IDNA_VARIANT_2003 veraltet. Sie wird derzeit als Standardwert für die Funktionen idn_to_ascii() und idn_to_utf8() verwendet. In PHP 7.4 wird dieser Standardwert in INTL_IDNA_VARIANT_UTS46 geändert und in der nächsten Hauptversion von PHP wird INTL_IDNA_VARIANT_2003 komplett entfernt.

Die Methode __autoload()

Die Methode __autoload() ist veraltet, weil sie der Funktion spl_autoload_register() unterlegen ist (sie ist nicht in der Lage, Autoloader zu verketten) und es keinerlei Interoperabilität zwischen den beiden Autoload-Verfahren gibt.

Die INI-Einstellung track_errors und die Variable $php_errormsg

Wenn die INI-Einstellung track_errors aktiviert ist, wird bei einem nicht-fatalen Fehler die Variable $php_errormsg im lokalen Bereich erstellt. Da solche Fehlerinformationen üblicherweise mit der Funktion error_get_last() abgefragt werden, ist diese Funktionalität nun veraltet.

Die Funktion create_function()

In Anbetracht der Sicherheitsprobleme dieser Funktion (sie ist ein schlanker Wrapper um eval()) ist diese Funktion nun veraltet. Stattdessen sollten anonyme Funktionen verwendet werden.

Die INI-Einstellung mbstring.func_overload

Da es in Umgebungen, in denen diese Einstellung aktiviert ist, Probleme bei der Interoperabilität mit zeichenkettenbasierten Funktionen gibt, ist sie nun veraltet.

Typumwandlung mit (unset)

Wird ein Ausdruck in diesen Typ umgewandelt, so ergibt dies immer null, weshalb diese überflüssige Typumwandlung nun veraltet ist.

parse_str() ohne zweiten Parameter

Wird die Funktion parse_str() ohne den zweiten Parameter verwendet, dann werden die Parameter aus der Abfragezeichenkette in der lokalen Symboltabelle abgelegt. In Anbetracht der damit verbundenen Sicherheitsrisiken ist die Verwendung von parse_str() ohne den zweiten Parameter nun veraltet. Die Funktion sollte immer mit zwei Parametern verwendet werden, da der zweite Parameter bewirkt, dass die Abfragezeichenkette in ein Array überführt wird.

Die Funktion gmp_random()

Diese Funktion generiert eine Zufallszahl basierend auf einem Bereich, der durch eine nicht näher spezifizierte, plattformspezifische Länge der einzelnen Elemente berechnet wird. Aus diesem Grund ist die Funktion nun veraltet. Um eine Zustallszahl unter Verwendung der Erweiterung GMP zu erzeugen, sollten stattdessen die Funktionen gmp_random_bits() und gmp_random_range() verwendet werden.

Die Funktion each()

Diese Funktion ist bei einer Iteration viel langsamer als ein gewöhnliches foreach und führt bei manchen Änderungen an PHP selbst zu Implementierungsproblemen, weshalb diese Funktion für veraltet erklärt wurde.

Übergabe einer Zeichenkette an assert()

Wenn assert() mit einer Zeichenkette als Parameter verwendet wird, muss die Zeichenkette mittels eval() ausgewertet werden. Angesichts des Potenzials für die Remote-Code-Ausführung ist die Übergabe einer Zeichenkette an assert() nun zugunsten der Verwendung boolescher Ausdrücke veraltet.

Der Parameter $errcontext bei Fehlerbehandlungen

Der Parameter $errcontext enthält alle lokalen Variablen der Stelle, an der der Fehler auftrat. Weil er nur selten verwendet wird und Probleme mit internen Optimierungen verursacht, ist es nun veraltet. Um Informationen über lokale Variablen am Ort des Fehlers abzurufen, sollte stattdessen ein Debugger verwendet werden,

Die Funktion read_exif_data()

Der Alias read_exif_data() ist veraltet. Stattdessen sollte die Funktion exif_read_data() verwendet werden.

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.


Sonstige Änderungen

utf8_encode() und utf8_decode() wurden verschoben

Die Funktionen utf8_encode() und utf8_decode() wurden nun als Stringfunktionen in die Standardbibliothek verschoben. In vorherigen Versionen war die Erweiterung XML erforderlich, damit sie verfügbar sind.

Änderungen bei mail() und mb_send_mail()

Bei den Funktionen mail() und mb_send_mail() akzeptiert der Parameter $additional_headers nun auch ein Array anstelle eines Strings.

LMDB-Unterstützung

Die Erweiterung DBA bietet nun Unterstützung für LMDB.

Änderungen am PHP-Build-System

  • Unix: Um PHP zu kompilieren, wird nun Autoconf 2.64 oder höher benötigt.
  • Unix: Für die Konfigurationsoption --with-pdo-oci wird die Versionsnummer des Oracle-Instant-Clients nicht mehr benötigt.
  • Unix: Die Konfigurationsoption --enable-gd-native-ttf wurde entfernt. Sie wurde seit PHP 5.5.0 nicht mehr verwendet.
  • Windows: Die Konfigurationsoption --with-config-profile wurde hinzugefügt. Damit lassen sich, vergleichbar mit der magischen Datei config.nice.bat, bestimmte Konfigurationen speichern.

Änderungen in GD

  • Die Funktion imageantialias() ist nun auch dann verfügbar, wenn PHP mit der libgd des Systems kompiliert wurde.
  • Die Funktion imagegd() speichert Truecolor-Bilder nun als echte Truecolor-Bilder; zuvor wurden sie in Palettenbilder umgewandelt.

MCrypt nach PECL verschoben

Die Erweiterung MCrypt wurde aus dem Kern nach PECL verschoben. Da die mcrypt-Bibliothek seit 2007 nicht mehr aktualisiert wurde, wird von ihrer Verwendung dringend abgeraten. Stattdessen sollte entweder OpenSSL oder Sodium verwendet werden.

session_module_name()

Bei der Funktion session_module_name() löst die Übergabe von "user" nun einen Fehler der Stufe E_RECOVERABLE_ERROR aus. Zuvor wurde dies stillschweigend ignoriert.

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 7.0.x nach PHP 7.1.x

Inhaltsverzeichnis

  • Neue Features
  • Neue Funktionen
  • Neue globale Konstanten
  • Nicht abwärtskompatible Änderungen
  • Veraltete Features in PHP 7.1.x
  • Geänderte Funktionen
  • Sonstige Änderungen
  • Windows-Unterstützung

Diese Nebenversion bringt einige neue Features und vereinzelte Inkompatibilitäten mit sich, auf die vor dem Versionswechsel in Produktivumgebungen getestet werden sollte.

Siehe auch die Migrationsleitfäden für PHP-Versionen 7.0.x.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

Nullable-Typen

Die Typen für Parameter und Rückgabewerte können nun durch ein vorangestelltes Fragezeichen als nullable gekennzeichnet werden. Das bedeutet, dass neben dem angegebenen Typ auch null als Parameter übergeben bzw. als Wert zurückgegeben werden kann.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void-Funktionen

Der Rückgabetyp void wurde eingeführt. Funktionen, die mit void als Rückgabetyp deklariert sind, müssen ihre return-Anweisung entweder ganz weglassen, oder eine leere return-Anweisung verwenden. null ist für eine void-Funktion kein gültiger Rückgabewert.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

null
int(2)
int(1)

Wenn versucht wird, den Rückgabewert einer void-Funktion zu verwenden, wird dieser einfach als null ausgewertet, ohne dass eine Warnung ausgegeben wird. Der Grund dafür ist, dass Warnungen die Verwendung übergeordneter generischer Funktionen zur Folge hätte.

Symmetrische Destrukturierung (Zerlegung) von Arrays

Die verkürzte Array-Syntax ([]) kann nun als Alternative zur bestehenden list()-Syntax verwendet werden, um Arrays für Zuweisungen zu zerlegen (auch innerhalb von foreach).

<?php
$data = [
[1, 'Tom'],
[2, 'Fred'],
];

// list()-Format
list($id1, $name1) = $data[0];

// []-Format
[$id1, $name1] = $data[0];

// list()-Format
foreach ($data as list($id, $name)) {
// der Code mit $id und $name
}

// []-Format
foreach ($data as [$id, $name]) {
// der Code mit $id und $name
}

Sichtbarkeit von Klassenkonstanten

Es ist nun möglich, den Geltungsbereich von Klassenkonstanten zu definieren.

<?php
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}

Der Pseudo-Typ iterable

Ein neuer Pseudo-Typ (analog zu callable) namens iterable wurde eingeführt. Er kann als Typ für Parameter und Rückgabe verwendet werden, wo er entweder Arrays oder Objekte akzeptiert, die die Schnittstelle Traversable implementieren. Bei abgeleiteten Typen kann der Parametertyp einer Kindklasse die Typen array und Traversable der Elternklasse auf iterable erweitern. Bei den Rückgabetypen kann eine Kindklasse den Rückgabetyp iterable der Elternklasse einschränken auf array oder ein Objekt, das Traversable implementiert.

<?php
function iterator(iterable $iter)
{
foreach ($iter as $val) {
//
}
}

Behandlung mehrerer Exceptions in einem Catch-Block

Ein catch-Block kann nun mehrere Exceptions abfangen, indem er sie durch Pipe-Zeichen (|) getrennt auflistet. Dies kann nützlich sein, wenn verschiedene Exceptions verschiedener Klassenebenen auf dieselbe Weise behandelt werden sollen.

<?php
try {
// etwas Code
} catch (FirstException | SecondException $e) {
// beide Exceptions behandeln
}

Unterstützung für Schlüssel in list()

Es ist nun möglich, Schlüssel mit list() oder mit der neuen verkürzten []-Syntax anzugeben. Damit lassen sich Arrays mit nicht-ganzzahligen oder nicht-sequenziellen Schlüsseln zerlegen.

<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];

// list()-Format
list("id" => $id1, "name" => $name1) = $data[0];

// []-Format
["id" => $id1, "name" => $name1] = $data[0];

// list()-Format
foreach ($data as list("id" => $id, "name" => $name)) {
// der Code mit $id und $name
}

// []-Format
foreach ($data as ["id" => $id, "name" => $name]) {
// der Code mit $id und $name
}

Unterstützung für negative Zeichenketten-Offsets

Bei den Funktionen für die Manipulation von Zeichenketten, die Offsets akzeptieren, können nun negative Zeichenketten-Offsets verwendet werden. Dies gilt auch für die Indizierung von Zeichenketten mit [] oder {}. In solchen Fällen wird ein negativer Offset als Offset relativ zum Ende der Zeichenkette interpretiert.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string (1) "e"
int(3)

Negative Zeichenketten- und Array-Offsets können nun auch in der einfachen Syntax zum Analysieren von Variablen innerhalb von Zeichenketten verwendet werden.

<?php
$string = 'bar';
echo "Das letzte Zeichen von '$string' ist '$string[-1]'.\n";
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Das letzte Zeichen von 'bar' ist 'r'.

Unterstützung für AEAD in ext/openssl

Durch Erweiterung der Funktionen openssl_encrypt() und openssl_decrypt() um zusätzliche Parameter wird nun AEAD (die Modi GCM und CCM) unterstützt.

Callables mit Closure::fromCallable() in Closures umwandeln

Der Klasse Closure wurde eine neue statische Methode hinzugefügt, mit der Callables einfach in Closure-Objekte umgewandelt werden können.

<?php
class Test
{
public function exposeFunction()
{
return Closure::fromCallable([$this, 'privateFunction']);
}

private function privateFunction($param)
{
var_dump($param);
}
}

$privFunc = (new Test)->exposeFunction();
$privFunc('irgendein Wert');

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(10) "irgendein Wert"

Asynchrone Signalverarbeitung

Eine neue Funktion namens pcntl_async_signals() wurde eingeführt, um eine asynchrone Signalverarbeitung ohne Verwendung von Ticks (die eine Menge zusätzliche Rechenzeit verursachen) zu ermöglichen.

<?php
pcntl_async_signals(true); // asynchrone Signale einschalten

pcntl_signal(SIGHUP, function($sig) {
echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

SIGHUP

Unterstützung für HTTP/2-Server-Push in ext/curl

Die Erweiterung CURL unterstützt nun "Server-Push" (erfordert Version 7.46 und höher). Dies kann durch die Funktion curl_multi_setopt() mit der neuen Konstante CURLMOPT_PUSHFUNCTION genutzt werden. Die Konstanten CURL_PUSH_OK und CURL_PUSH_DENY wurden ebenfalls hinzugefügt, damit die Ausführung des Server-Push-Callbacks entweder genehmigt oder verweigert werden kann.

Optionen für den Stream-Kontext

Die Stream-Kontext-Option tcp_nodelay wurde hinzugefügt.

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


Neue Funktionen

PHP-Kern

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


Neue globale Konstanten

Vordefinierte Kernkonstanten

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Datenfilterung

  • FILTER_FLAG_EMAIL_UNICODE

Bildverarbeitung und 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.


Nicht abwärtskompatible Änderungen

Übergabe von zu wenig Funktionsparametern löst Fehler aus

Bisher wurde eine Warnung ausgegeben, wenn eine benutzerdefinierte Funktion mit zu wenig Parametern aufgerufen wurde, nun wird statt einer Warnung eine Error-Exception ausgelöst. Diese Änderung gilt nur für benutzerdefinierte Funktionen und wirkt sich nicht auf interne Funktionen aus:

<?php
function test($param){}
test();

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Verbot dynamischer Aufrufe von Funktionen, die Geltungsbereiche untersuchen

Bei bestimten Funktionen sind dynamische Aufrufe (in der Form $func() oder array_map('extract', ...) usw.) nicht mehr zulässig. Dies gilt für Funktionen, die einen anderen Bereich prüfen oder ändern und dadurch ein mehrdeutiges und undefiniertes Verhalten verursachen. Von dieser Änderung sind folgende Funktionen betroffen:

  • assert() - mit einer Zeichenkette als erstem Parameter
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - mit einem Parameter
  • parse_str() - mit einem Parameter
<?php
(function () {
$func = 'func_num_args';
$func();
})();

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Ungültige Namen für Klassen, Schnittstellen und Traits

Die folgenden Bezeichnungen können nicht als Namen für Klassen, Schnittstellen oder Traits verwendet werden:

  • void
  • iterable

Umwandlung numerischer Zeichenketten berücksichtigt wissenschaftliche Notation

Ganzzahlige Operationen und Umwandlungen berücksichtigen bei numerischen Zeichenketten nun die wissenschaftliche Notation. Dies beinhaltet auch die Umwandlung per (int) und die folgenden Funktionen: intval() (mit Basis 10), settype(), decbin(), decoct() und dechex().

Korrekturen beim Algorithmus von mt_rand()

Die Funktion mt_rand() verwendet nun standardmäßig die korrigierte Version des Mersenne-Twister-Algorithmus. Bei Code, der sich auf die deterministische Ausgabe von mt_rand() verlässt, kann mt_srand() mit der Konstante MT_RAND_PHP als zweitem, optionalem Parameter verwendet werden, um das alte (fehlerhafte) Verhalten zu wiederherzustellen.

rand() und mt_rand() werden zu Aliasen für srand() bzw. mt_srand()

Die Funktionen rand() und srand()
sind nun Aliase für mt_rand() bzw.
mt_srand(). Das bedeutet, dass sich die Ausgabe der
folgenden Funktionen geändert hat: rand(),
shuffle(), str_shuffle() und
array_rand().

Das ASCII-Steuerzeichen Delete darf nicht in Bezeichnern verwendet werden

Das ASCII-Steuerzeichen Delete (0x7F) darf nicht mehr in Bezeichnern verwendet werden, die nicht in Anführungszeichen stehen.

Änderungen bei syslog als error_log

Wenn die INI-Einstellung error_log auf syslog gesetzt ist, werden die PHP-Fehlerstufen den entsprechenden Fehlerstufen von syslog zugeordnet. Dies führt im Vergleich zum vorherigen Ansatz, bei dem alle Fehler nur auf der Ebene der Benachrichtigung protokolliert wurden, zu einer feineren Differenzierung in den Fehlerprotokollen.

Destruktoren werden bei unvollständigen Objekten nicht aufgerufen

Für ein Objekt, das während der Ausführung seines Konstruktors eine Ausnahme auslöst, wird nun kein Destruktor mehr aufgerufen. Zuvor hing dieses Verhalten davon ab, ob das Objekt außerhalb des Konstruktors referenziert wurde (z. B. durch ein Exception-Backtrace).

Behandlung von per Referenz übegebenen Parametern durch call_user_func()

Die Funktion call_user_func() erzeugt nun immer eine Warnung, wenn sie für Funktionen aufgerufen wird, die Parameter per Referenz entgegennimmt. Vorher hing das Verhalten davon ab, ob der Aufruf vollständig definiert war oder nicht.

Außerdem unterbrechen call_user_func() und call_user_func_array() den Funktionsaufruf in diesem Fall nicht mehr. Es wird zwar die Warnung "expected reference" ausgegeben, aber der Aufruf wird wie gewohnt fortgesetzt.

Der leere Indexoperator ist nicht mehr auf Zeichenketten anwendbar

Die Anwendung des leeren Indexoperators auf eine Zeichenkette (z. B. $str[] = $x) führt zu einem fatalen Fehler. In früheren Versionen wurde die Zeichenkette stattdessen stillschweigend in ein Array umgewandelt.

Zuweisen eines Wertes an eine leere Zeichenkette über den Index der Zeichenkette

Eine Zeichenkette kann nun genauso verändert werden wie eine nicht-leere, d. h., wenn in einen Offset außerhalb der Zeichenkette geschrieben werden soll, wird dieser mit Leerzeichen aufgefüllt. Dabei werden nicht-ganzzahlige Typen in Integer umgewandelt und nur das erste Zeichen der zugewiesenen Zeichenkette wird verwendet. Zuvor wurden leere Zeichenketten stillschweigend wie ein leeres Array behandelt.

<?php
$a = '';
$a[10] = 'foo';
var_dump($a);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 7.0 folgende Ausgabe:

array(1) {
  [10]=>
  string(3) "foo"
}

Das oben gezeigte Beispiel erzeugt mit PHP 7.1 folgende Ausgabe:

string(11) "          f"

Entfernte INI-Direktiven

Die folgenden INI-Direktiven wurden entfernt:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Die Reihenfolge der Array-Elemente, die automatisch durch Referenzzuweisung erstellt werden, wurde geändert

Die Reihenfolge der Elemente, die in einem Array durch Zuweisung per Referenz automatisch erstellt wurden, hat sich geändert. Zum Beispiel:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 7.0 folgende Ausgabe:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Das oben gezeigte Beispiel erzeugt mit PHP 7.1 folgende Ausgabe:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sortierreihenfolge gleichwertiger Elemente

Aufgrund von Verbesserungen des internen Sortieralgorithmus kann sich die Sortierreihenfolge von Elementen, die beim Vergleich als gleichwertig betrachtet werden, im Vergleich zu vorherigen Versionen ändern.

Hinweis:

Es wird davon abgeraten, sich auf die Reihenfolge der Elemente, die als gleichwertig betrachtet werden, zu verlassen; sie kann sich jederzeit ändern.

Fehlermeldung für Fehler der Stufe E_RECOVERABLE

Die Fehlermeldung für Fehler der Stufe E_RECOVERABLE wurde von "Catchable fatal error" auf "Recoverable fatal error" geändert.

Der Parameter $options der Funktion unserialize()

Bei der Funktion unserialize() ist das Element allowed_classes des Parameters $options nun streng typisiert, d. h., wenn etwas anderes als ein Array oder ein Bool angegeben wird, gibt unserialize() false zurück und löst einen Fehler der Stufe E_WARNING aus.

Der Konstruktor der Klasse DateTime enthält nun Mikrosekunden

Die Klassen DateTime und DateTimeImmutable integrieren nun Mikrosekunden in korrekter Weise, wenn sie aus der aktuellen Zeit konstruiert werden, entweder explizit oder mit einer relativen Zeichenkette (z. B. "first day of next month"). Das bedeutet, dass einfache Vergleiche zweier neu erstellter Instanzen nun eher false zurückgeben als true:

<?php
new DateTime() == new DateTime();
?>

Umwandlungen fataler Fehler in Error-Exceptions

Wenn in der Erweiterung Date die serialisierten Daten für die Klassen DateTime oder DatePeriod nicht korrekt sind oder bei der Initialisierung der Zeitzone anhand der serialisierten Daten ein Fehler auftritt, wird von den Methoden __wakeup() oder __set_state() nun eine Error-Exception ausgelöst, statt einen fatalen Fehler zu verursachen.

In der Erweiterung DBA lösen Funktionen, mit denen Daten geändert werden können (z. B. dba_insert()) nun eine Error-Exception aus, statt einen abfangbaren fatalen Fehler zu verursachen, wenn der Schlüssel nicht genau zwei Elemente enthält.

In der Erweiterung DOM lösen ungültige Schema- oder RelaxNG-Validierungskontexte nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen. Auch der Versuch, eine Knotenklasse zu registrieren, die nicht die entsprechende Basisklasse erweitert oder der Versuch, eine ungültige Eigenschaft zu lesen oder eine schreibgeschützte Eigenschaft zu überschreiben, lösen nun ebenfalls eine Error-Exception aus.

In der Erweiterung IMAP lösen E-Mail-Adressen, die größer als 16385 Bytes sind, nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen.

Wenn in der Erweiterung Intl in einer Klasse, die die Klasse Collator erweitert, der übergeordnete Konstruktor nicht aufgerufen wird, bevor die übergeordneten Methoden aufgerufen werden, wird nun ein Error ausgelöst, statt einen wiederherstellbaren fatalen Fehler zu verursachen. Auch das Klonen eines Transliterator-Objekts löst nun eine Error-Exception aus, wenn das Klonen des internen Transliterators fehlschlägt, statt einen fatalen Fehler zu verursachen.

Wenn in der Funktion ldap_batch_modify() der Erweiterung LDAP ein unbekannter Änderungstyp angegeben wird, wird nun eine Error-Exception ausgelöst, statt einen fatalen Fehler zu verursachen.

In der Erweiterung mbstring lösen die Funktionen mb_ereg() und mb_eregi() nun eine ParseError-Exception aus, wenn ein ungültiger PHP-Ausdruck angegeben wird und wenn die Option 'e' verwendet wird.

In der Erweiterung Mcrypt lösen die Funktionen mcrypt_encrypt() und mcrypt_decrypt() nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen, wenn mcrypt nicht initialisiert werden kann.

Wenn in der Erweiterung mysqli versucht wird, eine ungültige Eigenschaft zu lesen oder eine schreibgeschützte Eigenschaft zu überschreiben, wird nun eine Error-Exception ausgelöst, statt einen fatalen Fehler zu verursachen.

Wenn in der Erweiterung Reflection ein Reflection-Objekt oder eine Objekteigenschaft nicht abgerufen werden kann, wird nun eine Error-Exception ausgelöst, statt einen fatalen Fehler zu verursachen.

In der Erweiterung Session löst ein benutzerdefinierter Session-Handler, der keine Zeichenkette für die Session-ID zurückgibt, nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen, wenn eine Funktion aufgerufen wird, die eine Sesion-ID erzeugen muss.

In der Erweiterung SimpleXML löst das Erstellen eines unbenannten oder doppelten Attributs nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen.

In der Erweiterung SPL löst der Versuch, ein SplDirectory-Objekt zu klonen, nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen. Auch der Aufruf der Methode ArrayIterator::append() während über ein Objekt iteriert wird, löst nun eine Error-Exception aus.

In der Standarderweiterung löst die Funktion assert() nun eine ParseError-Exception aus, statt einen abfangbaren fatalen Fehler zu verursachen, wenn ihr als erster Parameter eine Zeichenkette mit ungültigem PHP-Code übergeben wird. Auch der Aufruf der Funktion forward_static_call() außerhalb eines Klassenbereichs löst nun eine Error-Exception aus.

Wenn in der Erweiterung Tidy versucht wird, einen tidyNode manuell zu erstellen, wird nun eine Error-Exception ausgelöst, statt einen fatalen Fehler zu verursachen.

In der Erweiterung WDDX löst eine zirkuläre Referenz bei der Serialisierung nun eine eine Error-Exception aus, statt einen fatalen Fehler zu verursachen.

In der Erweiterung XML-RPC löst eine zirkuläre Referenz bei der Serialisierung nun eine eine Error-Exception aus, statt einen fatalen Fehler zu verursachen.

In der Erweiterung Zip löst die Methode ZipArchive::addGlob() nun eine Error-Exception aus, statt einen fatalen Fehler zu verursachen, wenn Glob nicht unterstützt wird.

Lexikalisch gebundene Variablen können Namen nicht mehrfach verwenden

Variablen, die über das use-Konstrukt an eine Closure gebunden sind, können weder $this noch den Namen irgendwelcher superglobals oder Parameter verwenden. Die folgenden Funktionsdefinitionen führen zum Beispiel alle zu einem fatalen Fehler:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

Änderung des Parametertyps bei long2ip()

Die Funktion long2ip() erwartet nun einen Parameter vom Typ int statt vom Typ string.

JSON-Kodierung und -Dekodierung

Die INI-Einstellung serialize_precision steuert nun die Genauigkeit der Serialisierung bei der Kodierung von Floats (Gleitkommazahlen).

Die Dekodierung eines leeren Schlüssels führt nun zu einem leeren Eigenschaftsnamen anstelle von _empty_.

<?php
var_dump(json_decode(json_encode(['' => 1])));

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

Wenn das Flag JSON_UNESCAPED_UNICODE an die Funktion json_encode() übergeben wird, werden nun die Sequenzen U+2028 und U+2029 maskiert.

Änderungen der Semantik der Parameter bei mb_ereg() und mb_eregi()

Der dritte Parameter der Funktionen mb_ereg() und mb_eregi() (regs) wird nun auf ein leeres Array gesetzt, wenn es keine Übereinstimmung gab. Zuvor wurde der Parameter nicht geändert.

Unterstützung für sslv2-Streams entfernt

Der sslv2-Stream wurde nun aus OpenSSL entfernt.

Verbot von "return;" für typisierte Rückgaben bereits bei der Kompilierung

In einer Funktion, die einen Rückgabetyp deklariert, löst eine return-Anweisung ohne Argument nun einen E_COMPILE_ERROR aus (außer der Rückgabetyp ist als void deklariert), auch wenn die return-Anweisung nie erreicht wird.

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


Veraltete Features in PHP 7.1.x

ext/mcrypt

Die Erweiterung mcrypt wurde seit fast einem Jahrzehnt nicht mehr weiterentwickelt und war auch ziemlich komplex in der Anwendung. Sie wurde daher zugunsten von OpenSSL aufgegeben. mcrypt wird in PHP 7.2 aus dem Kern entfernt und nach PECL verschoben.

Eval-Option für mb_ereg_replace() und mb_eregi_replace()

Bei den Funktionen mb_ereg_replace() und mb_eregi_replace() ist der Modifikator e für das Suchmuster veraltet.

User Contributed Notes

There are no user contributed notes for this page.


Geänderte Funktionen

PHP-Kern

  • Die Funktion getopt() hat einen optionalen dritten Parameter, der den Index des nächsten zu verarbeitenden Elements des Argumentvektors liefert. Dies erfolgt über einen Referenzparameter.
  • Bei der Funktion getenv() ist der Parameter nicht mehr zwingend erforderlich. Wenn er weggelassen wird, werden die aktuellen Umgebungsvariablen als assoziatives Array zurückgegeben.
  • Die Funktion get_headers() hat nun einen zusätzlichen Parameter, mit dem die Übergabe von benutzerdefinierten Stream-Kontexten möglich ist.
  • Die Funktion output_reset_rewrite_vars() setzt die URL-Rewrite-Variablen der Session nicht mehr zurück.
  • Die Funktion parse_url() ist nun restriktiver und unterstützt RFC3986.
  • Die Funktion unpack() akzeptiert nun einen optionalen dritten Parameter, um den Offset angeben zu können, ab dem entpackt werden soll.

Dateisystem

  • Die Funktion file_get_contents() akzeptiert für durchsuchbare Streams nun einen negativen Offset für die Suche.
  • Die Funktion tempnam() gibt nun eine Meldung aus, wenn sie auf das temporäre Verzeichnis des Systems zurückgreift.

JSON

  • Die Funktion json_encode() akzeptiert nun die neue Option JSON_UNESCAPED_LINE_TERMINATORS, mit der die Maskierung von U+2028- und U+2029-Zeichen deaktiviert werden kann, wenn JSON_UNESCAPED_UNICODE übergeben wird.

Multibyte-Zeichenketten

  • Die Funktion mb_ereg() weist nun ungültige Byte-Sequenzen zurück.
  • Die Funktion mb_ereg_replace() weist nun ungültige Byte-Sequenzen zurück.

PDO

  • Die Methode PDO::lastInsertId() löst bei PostgreSQL nun einen Fehler aus, wenn nextval noch nicht für die aktuelle Sitzung (die Postgres-Verbindung) aufgerufen wurde.

PostgreSQL

  • Die Funktion pg_last_notice() akzeptiert nun einen optionalen Parameter, mit dem eine Operation angegeben werden kann. Dies kann mit einer der folgenden neuen Konstanten erfolgen: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL oder PGSQL_NOTICE_CLEAR.
  • Die Funktion pg_fetch_all() akzeptiert nun einen optionalen zweiten Parameter, mit dem der Ergebnistyp angegeben werden kann (ähnlich dem dritten Parameter bei pg_fetch_array()).
  • Die Funktion pg_select() akzeptiert nun einen optionalen vierten Parameter, mit dem der Ergebnistyp angegeben werden kann (ähnlich dem dritten Parameter bei pg_fetch_array()).

Session

  • Die Funktion session_start() gibt nun false zurück und initialisiert $_SESSION nicht mehr, wenn die Session nicht gestartet werden konnte.

User Contributed Notes

There are no user contributed notes for this page.


Sonstige Änderungen

Meldungen und Warnungen bei Rechenoperationen mit ungültigen Zeichenketten

Es wurden neue Fehler der Stufen E_WARNING und E_NOTICE hinzugefügt, die ausgelöst werden, wenn mit Operatoren, die Zahlen erwarten (+ - * / ** % << >> | & ^) oder mit deren entsprechenden Zuweisungen ungültige Zeichenketten erzwungen werden. Ein Fehler der Stufe E_NOTICE wird ausgelöst, wenn eine Zeichenkette mit einem numerischen Wert beginnt, aber nachfolgende nicht-numerische Zeichen enthält, und ein Fehler der Stufe E_WARNING wird ausgelöst, wenn eine Zeichenkette keinen numerischen Wert enthält.

<?php
'1b' + 'something';

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Warnung beim Überlauf einer oktalen Maskierungs-Sequenz

Bisher wurde keine Warnung ausgegeben, wenn eine Maskierungs-Sequenz in oktaler Notation überlief. Nun läuft sie immer noch über, löst aber in diesem Fall einen Fehler der Stufe E_WARNING aus.

<?php
var_dump("\500");

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Unstimmigkeiten bei $this behoben

Während $this in PHP als spezielle Variable betrachtet wird, fehlte es an geeigneten Überprüfungen, um sicherzustellen, dass es nicht als Variablenname verwendet oder neu zugewiesen wird. Dies wurde nun korrigiert, sodass $this keine benutzerdefinierte Variable mehr sein kann, keinen anderern Wert zugewiesen bekommt und nicht mehr globalisiert werden kann.

Erzeugung von Session-IDs ohne Hashing

Session-IDs werden bei der Erzeugung nicht mehr gehasht. Wegen dieser Änderung wurden die folgenden vier INI-Einstellungen entfernt:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Außerdem wurden die folgenden zwei neuen INI-Einstellungen hinzugefügt:

  • session.sid_length - definiert die Länge der Session-ID. Aus Gründen der Abwärtskompatibilität ist der Standardwert 32 Zeichen.
  • session.sid_bits_per_character - definiert die Anzahl von Bits, die pro Zeichen gespeichert werden sollen (d. h. mit diesem Wert kann der für die Session-ID zulässige Wertebereich erlaubter Zeichen erhöht werden). Aus Gründen der Abwärtskompatibilität ist der Standardwert 4.

Änderungen bei der Handhabung von INI-Dateien

precision

Wenn der Wert auf -1 gesetzt wird, dann wird der dtoa-Modus 0 verwendet. Der Standardwert ist weiterhin 14.

serialize_precision

Wenn der Wert auf -1 gesetzt wird, dann wird der dtoa-Modus 0 verwendet. Der Standardwert ist nun -1.

gd.jpeg_ignore_warning

Der Standardwert für diese php.ini-Einstellung wurde auf 1 geändert, sodass libjpeg-Warnungen in der Standardeinstellung ignoriert werden.

opcache.enable_cli

Der Standardwert für diese php.ini-Einstellung wurde in PHP 7.1.2 auf 1 (aktiviert) gesetzt und in PHP 7.1.7 wieder auf 0 (deaktiviert).

Erzeugung der Session-ID nur mit einem CSPRNG

Session-IDs werden nun nur noch mit einem CSPRNG erzeugt.

Aussagekräftigere TypeError-Meldungen, wenn null erlaubt ist

Bei Typüberprüfungen durch arg_info geben TypeError-Exceptions nun aussagekräftigere Fehlermeldungen aus. Wenn der Parametertyp oder der Rückgabetyp null akzeptiert (indem er entweder einen Standardwert von null hat oder ein nullable-Typ ist), dann wird dies nun in der Fehlermeldung mit einem Hinweis wie "must be ... or null" oder "must ... or be null" erwähnt.

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-Unterstützung

Unterstützung für lange Pfade und UTF-8-Pfade

Wenn eine Webanwendung UTF-8-konform ist, sind keine weiteren Maßnahmen erforderlich. Für Anwendungen, die auf Pfade angewiesen sind, die nicht UTF-8-kodiert sind, muss eine explizite INI-Direktive gesetzt werden. Die Prüfung der INI-Einstellungen für die Kodierung hängt von der Reihenfolge im Kern ab:

  • internal_encoding
  • default_charset
  • zend.multibyte

Es wurden mehrere Funktionen zur Handhabung von Codepages eingeführt:

  • sapi_windows_cp_set(), um die Standard-Codepage festzulegen
  • sapi_windows_cp_get(), um die aktuelle Codepage abzurufen
  • sapi_windows_cp_is_utf8()
  • sapi_windows_cp_conv(), um unter Verwendung einer mit iconv() kompatiblen Signatur zwischen Codepages zu konvertieren

Diese Funktionen sind threadsicher.

Die Codepage für die Konsolenausgabe wird abhängig von der intern in PHP verwendeten Kodierung festgelegt. Je nach konkreter OEM-Codepage des Systems kann die sichtbare Ausgabe korrekt sein oder nicht. Zum Beispiel wird die Ausgabe in der standardmäßigen cmd.exe und auf einem System mit der OEM-Codepage 437 in den Codepages 1251, 1252, 1253 und einigen anderen korrekt angezeigt, wenn UTF-8 verwendet wird. Auf dem gleichen System werden Zeichen in Codepages wie 20932 wahrscheinlich nicht korrekt angezeigt. Dies hängt ab von den jeweiligen Systemregel für die Codepage, der Kompatibilität der Schriftart und dem verwendeten Konsolenprogramm. PHP konfiguriert die Codepage der Konsole automatisch gemäß den Kodierungsregeln der php.ini. In manchen Fällen kann es das Ergebnis verbessern, wenn eine andere Konsole verwendet wird als cmd.exe selbst.

Es ist jedoch zu beachten, dass ein Wechsel der Codepage zur Laufzeit nach dem Start der Anfrage unerwartete Nebeneffekte auf die CLI haben kann. Die bevorzugte Methode führt über die php.ini. Wenn PHP-CLI in einem Konsolen-Emulator verwendet wird, der kein Unicode unterstützt, kann dieser Weg notwendig sein, um eine Änderung der Konsolenkodierung zu vermeiden. Um dies zu erreichen, wird empfohlen, die Standard- oder interne Kodierung entsprechend der ANSI-Codepage einzustellen. Eine Alternative ist, die INI-Direktiven output_encoding und input_encoding auf die gewünschte Codepage zu setzen, wobei in diesem Fall der Unterschied zwischen interner und E/A-Codepage jedoch wahrscheinlich zu Zeichensalat führt. In seltenen Fällen kann es vorkommen, dass bei einem Absturz von PHP die ursprüngliche Konsolen-Codepage möglicherweise nicht wiederhergestellt wird. In diesem Fall kann der Befehl chcp verwendet werden, um sie manuell wiederherzustellen.

Besondere Vorsicht ist bei DBCS-Systemen (Systeme mit Doublebyte-Characterset) geboten - die Codepage zur Laufzeit mittels ini_set() zu ändern, kann zu Darstellungsproblemen führen. Der Unterschied zu Nicht-DBCS-Systemen ist, dass die erweiterten Zeichen zwei Konsolenzellen für die Anzeige benötigen. In bestimmten Fällen kann es vorkommen, dass Zeichen in den Glyphensatz der Schriftart abgebildet werden, ohne die Schriftart zu ändern. Dies liegt in der Natur der DBCS-Systeme und die einfachste Methode, Darstellungsprobleme zu vermeiden, besteht darin, die Codepage nicht per ini_set() zu ändern.

Infolge der Unterstützung von UTF-8 in den Streams sind PHP-Skripte nicht mehr auf ASCII- oder ANSI-Dateinamen beschränkt. Dies wird standardmäßig von CLI unterstützt. Für andere SAPIs ist die Dokumentation für den entsprechenden Server hilfreich.

Die Unterstützung langer Pfade ist transparent. Pfaden, die mehr als 260 Bytes haben, wird automatisch ein \?\ vorangestellt. Die maximale Pfadlänge ist auf 2048 Bytes begrenzt. Es ist zu beachten, dass die Begrenzung der Pfadsegmente (Länge des Basisnamens) weiterhin gilt.

Um die beste Portabilität zu erreichen, wird dringend empfohlen, für Dateinamen, I/O und andere verwandte Themen UTF-8 zu verwenden. Außerdem ist für Konsolenanwendungen eine TrueType-Schriftart zu bevorzugen. Darüber hinaus wird davon abgeraten, ini_set() für für die Änderung der Codepage zu verwenden.

readline

Die Erweiterung readline wird nun von der » WinEditLine-Bibliothek unterstützt, wodurch die interaktive CLI-Shell nun ebenfalls unterstützt wird (php.exe -a).

PHP_FCGI_CHILDREN

Die Umgebungsvariable PHP_FCGI_CHILDREN wird nun berücksichtigt. Wenn sie definiert ist, führt der erste php-cgi.exe-Prozess die angegebene Anzahl von Unterprozessen aus. Diese teilen sich denselben TCP-Socket.

ftok()

Die Unterstützung für ftok() wurde hinzugefügt

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 5.6.x nach PHP 7.0.x

Inhaltsverzeichnis

  • Nicht abwärtskompatible Änderungen
  • Neue Features
  • Veraltete Features in PHP 7.0.x
  • Geänderte Funktionen
  • Neue Funktionen
  • Neue Klassen und Interfaces
  • Neue globale Konstanten
  • Änderungen in SAPI-Modulen
  • Entfernte Erweiterungen und SAPIs
  • Sonstige Änderungen

Obwohl PHP 7.0 eine neue Hauptversion darstellt, wurde viel Wert auf eine einfache Migration gelegt. In dieser Version wurden hauptsächlich vorher als missbilligt markierte Funktionalität entfernt und die Sprachkonsistenz erhöht.

Trotzdem gibt es kleinere Inkompatibilitäten und neue Features, auf die geachtet werden muss und verschiedene Tests erforderlich machen, bevor in Produktivumgebungen auf eine andere PHP-Version gewechselt werden kann.

User Contributed Notes

There are no user contributed notes for this page.


Nicht abwärtskompatible Änderungen

Änderungen im Umgang mit Fehlern und Exceptions

Viele schwerwiegende und wiederherstellbare schwerwiegende Fehler wurden in PHP 7 in Exceptions umgewandelt. Diese Fehler-Exceptions erben von der Klasse Error, die ihrerseits die Schnittstelle Throwable implementiert (die neue Basisschnittstelle, die alle Exceptions erben).

Das bedeutet, dass benutzerdefinierte Funktionen für die Fehlerbehandlung eventuell nicht mehr ausgelöst werden, da stattdessen Exceptions ausgelöst werden (was neue schwerwiegende Fehler für nicht abgefangene Error-Exceptions verursacht).

Eine genauere Beschreibung der Funktionsweise von Fehlern in PHP 7 ist auf der Seite Fehler in PHP 7 zu finden. Dieser Migrationsleitfaden zählt lediglich die Änderungen auf, die die Abwärtskompatibilität betreffen.

Bei der Funktion set_exception_handler() ist nicht mehr gewährleistet, dass sie Exception-Objekte erhält.

Code, der einen Exception-Handler mit der Funktion set_exception_handler() unter Verwendung einer Deklaration vom Typ Exception implementiert, führt zu einem fatalen Fehler, wenn ein Error-Objekt ausgelöst wird.

Wenn der Handler sowohl mit PHP 5 als auch mit PHP 7 funktionieren soll, sollte die Typdeklaration aus dem Handler entfernt werden. Bei Code, der migriert wird, um nur unter PHP 7 zu funktionieren, genügt es stattdessen, die Exception-Typdeklaration durch Throwable zu ersetzen.

<?php
// PHP-Code, der nicht mehr funktioniert
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 und 7 kompatibel
function handler($e) { ... }

// Nur PHP 7
function handler(Throwable $e) { ... }
?>

Interne Konstruktoren lösen bei Fehlern immer Exceptions aus

Zuvor gaben einige interne Klassen null oder ein unbrauchbares Objekt zurück, wenn der Konstruktor fehlschlug. Alle internen Klassen lösen nun in einem solchen Fall eine Exception aus, so wie es die benutzerdefinierten Klassen bereits tun.

Parser-Fehler lösen ParseError aus

Parser-Fehler erzeugen nun ein ParseError-Objekt. Die Fehlerbehandlung für eval() sollte einen catch-Block enthalten, der diesen Fehler behandeln kann.

Änderungen des Schweregrads von E_STRICT-Meldungen

Alle E_STRICT-Meldungen wurden neu eingestuft. Die Konstante E_STRICT wurde beibehalten, sodass Aufrufe wie error_reporting(E_ALL|E_STRICT) keinen Fehler verursachen.

Änderungen des Schweregrads von E_STRICT-Meldungen
Situation | Neue Stufe/Verhalten
Indizierung durch eine Ressource | E_NOTICE
Abstrakte statische Methoden | Hinweis entfernt, löst keinen Fehler aus
"Neudefinieren" eines Konstruktors | Hinweis entfernt, löst keinen Fehler aus
Inkompatible Signaturen bei der Vererbung | E_WARNING
Gleiche (kompatible) Eigenschaft in zwei verwendeten Traits | Hinweis entfernt, löst keinen Fehler aus
Nicht-statischer Zugriff auf eine statische Eigenschaft | E_NOTICE
Nur Variablen sollten per Referenz zugewiesen werden | E_NOTICE
Nur Variablen sollten per Referenz übergeben werden | E_NOTICE
Statischer Aufruf nicht-statischer Methoden | E_DEPRECATED

Änderungen beim Umgang mit Variablen

PHP 7 verwendet nun beim Parsen von Quelldateien einen abstrakten Syntaxbaum. Dies hat viele Verbesserungen an der Sprache ermöglicht, die zuvor aufgrund der Einschränkungen des Parsers in früheren PHP-Versionen nicht möglich waren. Allerdings hat das auch dazu geführt, dass einige Spezialfälle aus Gründen der Konsistenz entfernt wurden, was Brüche in der Abwärtskompatibilität zur Folge hat. Diese Fälle werden in diesem Abschnitt detailliert beschrieben.

Änderungen beim Umgang mit indirekten Variablen, Eigenschaften und Methoden

Der indirekte Zugriff auf Variablen, Eigenschaften und Methoden wird nun in strikter Reihenfolge von links nach rechts ausgewertet. In früheren Versionen war die Reihenfolge der Auswertung in einigen Fällen umgekehrt. Die folgende Tabelle zeigt, wie sich die Reihenfolge der Auswertung geändert hat.

Alte und neue Auswertung indirekter Ausdrücke
Ausdruck | Auswertung in PHP 5 | Auswertung in 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']()

Code, der die alte Auswertungsreihenfolge von rechts nach links verwendet, muss mit geschweiften Klammern umgeschrieben werden, um explizit diese Auswertungsreihenfolge zu verwenden (siehe die obige mittlere Spalte). Dadurch wird der Code sowohl vorwärtskompatibel mit PHP 7.x als auch rückwärtskompatibel mit PHP 5.x.

Dies betrifft auch das Schlüsselwort global. Falls erforderlich, kann die Syntax mit den geschweiften Klammern verwendet werden, um das frühere Verhalten zu emulieren:

<?php
function f() {
// Nur in PHP 5 gültig.
global $$foo->bar;

// In PHP 5 und 7 gültig.
global ${$foo->bar};
}
?>

Änderungen im Umgang mit der Funktion list()

list() weist Variablen nicht mehr in umgekehrter Reihenfolge zu

list() weist den Variablen nun Werte in der Reihenfolge zu, in der sie definiert sind, und nicht mehr in umgekehrter Reihenfolge. Wie unten gezeigt, betrifft dies im Allgemeinen nur Fälle, in denen list() in Verbindung mit dem Array-Operator [] verwendet wird:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

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

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

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

Im Allgemeinen ist es nicht empfehlenswert, sich auf die Reihenfolge zu verlassen, in der die Zuweisungen mit list() erfolgen. Das ist ein Implementierungs-Detail, das sich in der Zukunft wieder ändern kann.

Leere list()-Zuweisungen wurden entfernt

list()-Konstrukte dürfen nicht mehr leer sein; die Folgenden sind nicht mehr erlaubt:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() kann keine Strings entpacken

list() kann Variablen vom Typ string nicht mehr entpacken. Stattdessen sollte str_split() verwendet werden.

Änderung der Reihenfolge von Array-Elementen, die automatisch durch Zuweisung per Referenz erzeugt werden

Die Reihenfolge der Elemente eines Arrays, die automatisch durch Zuweisung per Referenz erstellt werden, hat sich geändert. Zum Beispiel:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Klammern um Funktionsparameter haben keinen Einfluss mehr auf das Verhalten

Wenn in PHP 5 redundante Klammern um Funktionsparameter verwendet wurden, konnte die Warnung wegen strikter Standards unterdrückt werden, indem der Parameter per Referenz übergeben wurde. Nun wird die Warnung immer angezeigt.

<?php
function getArray() {
return [1, 2, 3];
}

function squareArray(array &$a) {
foreach ($a as &$v) {
$v **= 2;
}
}

// Erzeugt in PHP 7 eine Warnung.
squareArray((getArray()));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Änderungen bei foreach

Am Verhalten der Kontrollstruktur foreach wurden kleinere Änderungen vorgenommen, die sich vor allem auf die Handhabung des internen Array-Zeigers und auf die Änderung des Arrays, über das iteriert wird, beziehen.

foreach ändert den internen Array-Zeiger nicht mehr

Vor PHP 7 wurde der interne Array-Zeiger verändert, während mit foreach über ein Array iteriert wurde. Dies ist nun, wie im folgenden Beispiel gezeigt wird, nicht mehr der Fall:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

int(1)
int(2)
bool(false)

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

int(0)
int(0)
int(0)

foreach iteriert bei Übergabe per Wert über eine Kopie des Arrays

Wenn foreach im Standardmodus Pass-by-Value verwendet wird, arbeitet es nun mit einer Kopie des Arrays, über das iteriert wird, und nicht mit dem Array selbst. Das bedeutet, dass Änderungen, die während des Iterierens am Array vorgenommen werden, keine Auswirkungen auf die iterierten Werte haben.

Verbessertes Iterationsverhalten von foreach bei Übergabe per Referenz

Bei der Iteration per Referenz kann foreach Änderungen, die während des Iterierens am Array vorgenommen werden, nun besser verfolgen. Wenn zum Beispiel während des Iterierens etwas an das Array angehängt wird, führt das dazu, dass nun auch über die angehängten Werte iteriert wird:

<?php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

int(0)

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

int(0)
int(1)

Iteration über nicht-Traversable Objekte

Die Iteration über Objekte, die Traversable nicht implementieren, verhält sich nun genauso wie die Iteration über Arrays per Referenz. Dies führt dazu, dass das verbesserte Verhalten, wenn sich ein Array während des Iterierens ändert auch angewendet wird, wenn Eigenschaften zum Objekt hinzugefügt oder daraus entfernt werden.

Änderungen im Umgang mit dem Typ int

Ungültige oktale Literale

Bisher wurden oktale Literale, die ungültige Zahlen enthielten, stillschweigend abgeschnitten (0128 wurde als 012 interpretiert). Nun verursacht ein ungültiges Oktal-Literal einen Parser-Fehler.

Negative Bitverschiebungen

Bitweises Verschieben um negative Zahlen führt nun zu einem ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

int(0)

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

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

Bitverschiebungen außerhalb des zulässigen Bereichs

Bitweise Verschiebungen (in beide Richtungen) über die Bitbreite eines int ergeben immer 0. Bisher war das Verhalten solcher Verschiebungen von der Architektur abhängig.

Änderungen bei der Division durch Null

Wenn 0 beim Divisionsoperator (/) oder beim Modulusoperator (%) als Divisor verwendet wird, wurde bisher einen Fehler der Stufe E_WARNING ausgegeben und false zurückgegeben. Nun gibt der Divisionsoperator, wie in IEEE 754 festgelegt, eine Gleitkommazahl entweder als +INF, -INF oder NAN zurück. Der Modulusoperator gibt nun kein E_WARNING mehr aus, sondern löst stattdessen eine DivisionByZeroError-Exception aus.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

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)

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

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

Änderungen im Umgang mit dem Typ string

Hexadezimale Zeichenketten werden nicht mehr als numerisch betrachtet

Zeichenketten, die hexadezimale Zahlen enthalten, gelten nicht mehr als numerisch. Zum Beispiel:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

bool(true)
bool(true)
int(15)
string(2) "oo"

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

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() kann verwendet werden, um zu prüfen, ob ein string eine hexadezimale Zahl enthält, und auch zur Umwandlung einer Zeichenkette dieses Typs zu einem int:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
throw new Exception("Ungültige Ganzzahl!");
}
var_dump($int); // int(65535)
?>

\u{ kann zu Fehlern führen

Mit der Einführung der neuen Unicode-Codepoint-Maskierungssyntax verursachen Zeichenketten, die \u{ gefolgt von einer ungültigen Sequenz enthalten, einen fatalen Fehler. Um dies zu vermeiden, sollte der führende Rückwärtsstrich maskiert werden.

Entfernte Funktionen

call_user_method() und call_user_method_array()

Diese Funktionen sind seit PHP 4.1.0 zugunsten von call_user_func() und call_user_func_array() veraltet. Alternativ dazu können auch die Variablenfunktionen und/oder der Operator ... verwendet werden.

Alle ereg*-Funktionen

Alle ereg-Funktionen wurden entfernt. Es wird empfohlen, stattdessen PCRE zu verwenden.

Aliase bei mcrypt

Die veraltete Funktion mcrypt_generic_end() wurde zugunsten von mcrypt_generic_deinit() entfernt.

Darüber hinaus wurden die veralteten Funktionen mcrypt_ecb() mcrypt_cbc(), mcrypt_cfb() und mcrypt_ofb() zugunsten von mcrypt_decrypt() in Kombination mit der entsprechenden MCRYPT_MODE_*-Konstante entfernt.

Alle ext/mysql-Funktionen

Alle ext/mysql-Funktionen wurden entfernt. Details zur Auswahl einer anderen MySQL-API sind unter Auswahl einer API zu finden.

Alle ext/mssql-Funktionen

Alle ext/mssql-Funktionen wurden entfernt.

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • Unified ODBC API

Aliase bei intl

Die veralteten Aliase datefmt_set_timezone_id() und
IntlDateFormatter::setTimeZoneID() wurden
zugunsten von datefmt_set_timezone() bzw.
IntlDateFormatter::setTimeZone() entfernt.

set_magic_quotes_runtime()

Die Funktion set_magic_quotes_runtime() und ihr Alias magic_quotes_runtime() wurden entfernt. Sie sind seit PHP 5.3.0 veraltet und praktisch nutzlos, seit in PHP 5.4.0 die magischen Anführungszeichen entfernt wurden.

set_socket_blocking()

Der veraltete Alias set_socket_blocking() wurde zugunsten von stream_set_blocking() entfernt.

dl() in PHP-FPM

Die Funktion dl() kann in PHP-FPM nicht mehr verwendet werden. In CLI und integrierten SAPIs ist sie weiterhin verfügbar.

GD-Type1-Funktionen

Die PostScript-Type1-Schriftarten werden von der Erweiterung GD nicht mehr unterstützt. Infolgedessen wurden die folgenden Funktionen entfernt:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

Es wird empfohlen, stattdessen die TrueType-Schriftarten und die damit verbundenen Funktionen zu verwenden.

Entfernte INI-Direktiven

Entfernte Features

Die folgenden INI-Direktiven wurden entfernt, da ihre zugehörigen Funktionen ebenfalls entfernt wurden:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

Die Direktive xsl.security_prefs wurde entfernt. Stattdessen sollte die Methode XsltProcessor::setSecurityPrefs() aufgerufen werden, um die Sicherheitseinstellungen auf Basis einzelner Prozessoren zu steuern.

Andere nicht abwärtskompatible Änderungen

Neue Objekte können nicht per Referenz zugewiesen werden

Es ist nicht mehr möglich, das Resultat einer new-Anweisung per Referenz einer Variablen zuzuweisen:

<?php
class C {}
$c =& new C;
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Ungültige Klassen-, Schnittstellen- und Traitnamen

Die folgenden Namen können nicht mehr zur Benennung von Klassen, Schnittstellen und Traits verwendet werden:

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

Darüber hinaus sollten auch die folgenden Namen nicht verwendet werden. Auch wenn sie in PHP 7.0 keinen Fehler erzeugen, sind sie für die zukünftige Verwendung reserviert und sollten als veraltet angesehen werden.

  • resource
  • object
  • mixed
  • numeric

ASP- und Skript-Tags wurden entfernt

Es ist nicht mehr möglich, ASP-ähnliche Tags oder Skript-Tags zu verwenden, um PHP-Code einzuschließen. Die folgenden Tags sind hiervon betroffen:

Entfernte ASP- und Skript-Tags
Öffnendes Tag | Schließendes Tag
<% | %>
<%= | %>
<script language="php"> | </script>

Aufrufe aus inkompatiblen Kontexten wurden entfernt

Ein statischer Aufruf einer nicht-statischen Methode aus einem inkompatiblen Kontext war bereits in PHP 5.6 veraltet und führt nun dazu, dass die aufgerufene Methode eine undefinierte $this-Variable hat und einen Veraltet-Hinweis ausgibt.

<?php
class A {
public function test() { var_dump($this); }
}

// Hinweis: Erweitert A NICHT
class B {
public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5.6 folgende Ausgabe:

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

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

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 ist nun ein rechtsassoziativer Operator

Das yield-Konstrukt ist nun rechtsassoziativ (Auswertung von rechts nach links) und es werden keine Klammern mehr benötigt. In der Rangfolge liegt es nun zwischen print und =>. Dadurch ändert sich das Verhalten wie folgt:

<?php
echo yield -1;
// Wurde zuvor interpretiert als
echo (yield) - 1;
// Und wird nun interpretiert als
echo yield (-1);

yield $foo or die;
// Wurde zuvor interpretiert als
yield ($foo or die);
// Und wird nun interpretiert als
(yield $foo) or die;
?>

Um Unklarheiten zu beseitigen, können Klammern verwendet werden.

Eine Funktion kann nicht mehrere Parameter mit demselben Namen haben

Es ist nicht mehr möglich, in einer Funktion mehrere Parameter mit demselben Namen zu definieren. Zum Beispiel führt eine Funktion wie die folgende zu einem E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
//
}
?>

Funktionen, die Parameter analysieren, melden den aktuellen Parameterwert

Die Funktionen func_get_arg(), func_get_args() und debug_backtrace() und Backtraces bei Exceptions melden nicht mehr den ursprünglichen Wert, der an einen Parameter übergeben wurde, sondern stattdessen den aktuellen Wert (der möglicherweise geändert wurde).

<?php
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);?>

Das oben gezeigte Beispiel erzeugt mit PHP 5 folgende Ausgabe:

1

Das oben gezeigte Beispiel erzeugt mit PHP 7 folgende Ausgabe:

2

Switch-Anweisungen können nicht mehrere default-Blöcke haben

Es ist nicht mehr möglich, zwei oder mehr default-Blöcke in einer switch-Anweisung zu definieren. Zum Beispiel löst die folgende switch-Anweisung einen E_COMPILE_ERROR aus:

<?php
switch (1) {
default:
break;
default:
break;
}
?>

$HTTP_RAW_POST_DATA wurde entfernt

$HTTP_RAW_POST_DATA ist nicht mehr verfügbar. Stattdessen sollte der php://input-Stream verwendet werden.

In INI-Dateien wurden Kommentare im #-Format entfernt

In INI-Dateien ist es nicht mehr möglich, Kommentare durch ein vorangestelltes # zu markieren. Stattdessen sollte ein ; (Semikolon) verwendet werden. Diese Änderung gilt nicht nur für die php.ini, sondern auch für Dateien, die von parse_ini_file() und parse_ini_string() verarbeitet werden.

Erweiterung JSON durch JSOND ersetzt

Die Erweiterung JSON wurde durch JSOND ersetzt, was zu drei kleineren Beeinträchtigungen in der Abwärtskompatibilität führt. Erstens darf eine Zahl nicht mit einem Dezimalpunkt enden (d. h. 34. muss entweder durch 34.0 oder 34 ersetzt werden). Zweitens darf bei Verwendung der wissenschaftlichen Notation der Exponent e nicht unmittelbar auf einen Dezimalpunkt folgen (d. h. 3.e3 muss entweder durch 3.0e3 oder 3e3 ersetzt werden). Und schließlich wird eine leere Zeichenkette nicht mehr als gültiges JSON angesehen.

Interne Funktionen schlagen bei Überlauf fehl

Bisher haben interne Funktionen Zahlen, die von Gleitkommazahlen in Ganzzahlen umgewandelt wurden, stillschweigend abgeschnitten, wenn die Gleitkommazahl zu groß war, um sie als Ganzzahl darzustellen. Nun wird ein Fehler der Stufe E_WARNING ausgegeben und null zurückgegeben.

Korrekturen bei Rückgabewerten von benutzerdefinierten Session-Handlern

Eine Prädikatsfunktion, die von einem benutzerdefinierten Session-Handler implementiert wird und entweder false oder -1 zurückgibt, löst einen schwerwiegenden Fehler aus. Ist ein von dieser Funktion zurückgegebener Wert nicht boolesch, -1 oder 0, schlägt die Funktion fehl und löst einen Fehler der Stufe E_WARNING aus.

Sortierreihenfolge gleichwertiger Elemente

Aufgrund von Verbesserungen des internen Sortieralgorithmus kann sich die Sortierreihenfolge von Elementen, die beim Vergleich als gleichwertig betrachtet werden, im Vergleich zu vorherigen Versionen ändern.

Hinweis:

Es wird davon abgeraten, sich auf die Reihenfolge der Elemente, die als gleichwertig betrachtet werden, zu verlassen; sie kann sich jederzeit ändern.

Falsch platzierte break- und continue-Anweisungen

break- und continue-Anweisungen außerhalb einer Schleife oder einer switch-Kontrollstruktur werden nun bei der Kompilierung erkannt, anstatt wie bisher zur Laufzeit, und lösen einen Fehler der Stufe E_COMPILE_ERROR aus.

Mhash ist keine Erweiterung mehr

Die Erweiterung Mhash wurde vollständig in die Erweiterung Hash integriert. Daher ist es nicht mehr möglich, mit extension_loaded() zu erkennen, ob Mhash unterstützt wird. Stattdessen sollte function_exists() verwendet werden. Darüber hinaus wird Mhash nicht mehr von get_loaded_extensions() und ähnlichen Funktionen gemeldet.

declare(ticks)

Die Directive declare(ticks) wird nicht mehr in verschiedene Kompilierungseinheiten übertragen.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

Deklaration skalarer Typen

Für die Deklaration des Typs von Skalaren gibt es zwei Möglichkeiten: erzwungen (Standard) und strikt. Die folgenden Typen können nun für Parameter erzwungen werden: Zeichenketten (string), Ganzzahlen (int), Gleitkommazahlen (float), und Booleans (bool). Sie ergänzen die anderen in PHP 5 eingeführten Typen: Klassennamen, Schnittstellen, array und callable.

<?php
// Erzwingender Modus
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(9)

Um den strikten Modus zu aktivieren, muss am Anfang der Datei eine einzelne declare-Direktive stehen. Das bedeutet, dass die Strenge der Typisierung für Skalare für jede Datei einzeln festgelegt wird. Diese Anweisung wirkt sich nicht nur auf die Typ-Deklarationen von Parametern aus, sondern auch auf den Rückgabetyp von Funktionen (siehe Deklaration des Rückgabetyps), auf eingebaute PHP-Funktionen und auf Funktionen von geladenen Erweiterungen.

Eine vollständige Dokumentation und Beispiele für die Deklaration von Skalartypen ist im Abschnitt über die Deklaration des Typs zu finden.

Deklaration des Rückgabetyps

PHP 7 unterstützt die Deklaration des Rückgabetyps. Ähnlich wie bei der Deklaration des Parameter-Typs gibt die Deklaration des Rückgabetyps den Typ des Wertes an, der von einer Funktion zurückgegeben wird. Für die Deklaration des Rückgabetyps stehen dieselben Typen zur Verfügung wie für die Deklaration des Parameter-Typs.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Eine vollständige Dokumentation und Beispiele für die Deklaration des Rückgabetyps ist im Abschnitt über die Deklaration des Rückgabetyps zu finden.

Null-Koaleszenz-Operator

Der null-Koaleszenz-Operator (etwa: Operator für die Kombination mit null) ?? wurde als syntaktische Vereinfachung hinzugefügt für den häufigen Fall, dass ein ternärer Operator in Verbindung mit isset() verwendet wird. Er gibt seinen ersten Operanden zurück, wenn er existiert und nicht null ist; andernfalls gibt er seinen zweiten Operanden zurück.

<?php
// Gibt den Wert von $_GET['user'] zurück, falls er existiert,
// und andernfalls 'nobody'.
$username = $_GET['user'] ?? 'nobody';
// Dies ist gleichbedeutend mit:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Dieser Operator kann verkettet werden. Das Beispiel gibt den
// ersten definierten Wert aus $_GET['user'], $_POST['user'] und
// 'nobody' zurück.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Raumschiff-Operator (Spaceship)

Der Raumschiff-Operator wird für den Vergleich zweier Ausdrücke verwendet. Er gibt -1, 0 oder 1 zurück, wenn $a kleiner, gleich oder größer ist als $b. Vergleiche werden gemäß den üblichen Regeln für Typenvergleiche in PHP durchgeführt.

<?php
// Ganzzahlen
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Gleitkommazahlen
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Zeichenketten
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Definieren von Array-Konstanten mit define()

Es ist nun möglich, Array-Konstanten mit define() zu definieren. Bis zu PHP 5.6 konnten Array-Konstanten nur mit const definiert werden.

<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);

echo ANIMALS[1]; // gibt "cat" aus
?>

Anonyme Klassen

Mit new class wurde die Unterstützung für anonyme Klassen hinzugefügt. Dies kann anstelle von vollständigen Klassendefinitionen verwendet werden für Objekte, die nur einmal benötigt werden:

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(class@anonymous)#2 (0) {
}

Die vollständige Dokumentation befindet sich im Abschnitt Anonyme Klassen.

Syntax für die Maskierung von Unicode-Codepunkten

Diese Syntax nimmt einen Unicode-Codepunkt in hexadezimaler Form und gibt diesen Codepunkt in UTF-8 in eine Zeichenkette mit doppelten Anführungszeichen oder einen Heredoc aus. Jeder gültige Codepunkt wird akzeptiert, wobei führende Nullen optional sind.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

ª
ª (wie zuvor, jedoch mit führenden Nullen)
?

Closure::call()

Die Methode Closure::call() ist ein leistungsfähigerer und kürzerer Weg, um den Gültigkeitsbereich eines Objekts vorübergehend an eine Closure zu binden und diese aufzurufen.

<?php
class A {private $x = 1;}

// Code vor PHP 7
$getX = function() {return $this->x;};
$getXCB = $getX->bindTo(new A, 'A'); // zwischengeschaltete Closure
echo $getXCB();

// Code in PHP 7+
$getX = function() {return $this->x;};
echo $getX->call(new A);

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1
1

Gefiltertes unserialize()

Dieser Mechanismus soll zusätzliche Sicherheit beim Deserialisieren von Objekten aus nicht vertrauenswürdigen Daten bieten. Durch die Definition einer Whitelist für Klassen, die deserialisiert werden dürfen, können Angriffe durch Code-Injection verhindert werden.

<?php

// wandelt alle Objekte in __PHP_Incomplete_Class-Objekte um
$data = unserialize($foo, ["allowed_classes" => false]);

// wandelt mit Ausnahme von MyClass und MyClass2 alle Objekte in __PHP_Incomplete_Class-Objekte um
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// In der Voreinstellung (entspricht dem Weglassen des zweiten Parameters) werden alle Klassen akzeptiert
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

Die neue Klasse IntlChar wurde hinzugefügt, um zusätzliche Funktionalitäten von ICU zu nutzen. Die Klasse selbst definiert eine Reihe von statischen Methoden und Konstanten, die zur Bearbeitung von Unicode-Zeichen verwendet werden können.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

10ffff
COMMERCIAL AT
bool(true)

Um diese Klasse verwenden zu können, muss die Erweiterung Intl installiert sein.

Expectations (Annahmen)

Die Expectations sind eine abwärtskompatible Weiterentwicklung der alten Funktion assert(). Sie ermöglichen Assertions ohne Leistungsverluste im Produktionscode und bieten die Möglichkeit, benutzerdefinierte Exceptions auszulösen, wenn eine Assertion fehlschlägt.

Während die alte API aus Kompatibilitätsgründen beibehalten wird, ist assert() nun ein Sprachkonstrukt, das es ermöglicht, dass der erste Parameter ein Ausdruck sein kann und nicht nur ein auszuwertender string-Wert oder ein zu testender bool)-Wert.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Irgendeine Fehlermeldung'));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Fatal error: Uncaught CustomError: Irgendeine Fehlermeldung

Alle Details zu diesem Feature, einschließlich der Konfiguration sowohl in Entwicklungs- als auch in Produktionsumgebungen, befinden sich auf der Handbuchseite des Sprachkonstrukts assert().

Zusammengefasste use-Deklarationen

Klassen, Funktionen und Konstanten, die aus demselben namespace importiert werden, können nun in einer einzigen use-Anweisung zusammengefasst werden.

<?php
// Code vor PHP 7
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// Code in 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};
?>

Generatoren können Werte zurückgeben

Dieses Feature baut auf der Generator-Funktionalität auf, die in PHP 5.5 eingeführt wurde. Sie ermöglicht es, eine return-Anweisung innerhalb eines Generators zu verwenden, damit der Wert eines Ausdrucks zurückgegeben werden kann (eine Rückgabe per Referenz ist nicht erlaubt). Dieser Wert kann mit der neuen Methode Generator::getReturn() abgerufen werden, die erst verwendet werden darf, nachdem der Generator die Ausgabe von Werten abgeschlossen hat.

<?php

$gen = (function() {
yield 1;
yield 2;

return 3;
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1
2
3

Die Möglichkeit, den Endwert eines Generators explizit zurückzugeben, ist sehr nützlich. Dadurch kann der Client-Code, der den Generator ausführt, den letzten vom Generator zurückgegebenen Wert (das Ergebnis einer Berechnung durch eine Art Co-Routine) als Sonderfall behandeln. Dies ist viel einfacher, als einen clientseitigen Code zu schreiben, der zunächst prüft, ob der zurückgegebene Wert der Letzte ist, und ihn dann gegebenenfalls als speziellen Wert behandelt.

Delegierung durch Generatoren

Generatoren können nun automatisch an einen anderen Generator, ein Traversable-Objekt oder ein Array delegieren, ohne dass Boilerplate (redundanter Code) in den äußersten Generator geschrieben werden muss. Dies wird durch die Verwendung des Konstrukts yield from erreicht.

<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}

function gen2()
{
yield 3;
yield 4;
}

foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

1
2
3
4

Ganzzahl-Division mit intdiv()

Die neue Funktion intdiv() führt eine Ganzzahl-Division ihrer Operanden durch und gibt das Ergebnis zurück.

<?php
var_dump(intdiv(10, 3));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(3)

Optionen für Session

Die Funktion session_start() akzeptiert nun ein Array von Optionen. Diese überschreiben die Session-Konfigurationsanweisungen, die normalerweise in der php.ini gesetzt werden.

Diese Optionen unterstützen nun auch session.lazy_write. Diese Option ist standardmäßig aktiviert und bewirkt, dass PHP eine Session-Datei nur dann überschreibt, wenn sich die Session-Daten geändert haben. Außerdem wurde die Option read_and_close hinzugefügt. Sie kann nur an session_start() übergeben werden und gibt an, dass die Session-Daten gelesen werden sollen und die Session dann sofort unverändert geschlossen werden soll.

Um zum Beispiel session.cache_limiter auf private zu setzen und die Session nach dem Lesen sofort zu schließen, kann Folgendes verwendet werden:

<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>

preg_replace_callback_array()

Wenn die Funktion preg_replace_callback() verwendet werden müsste, kann stattdessen mit der neuen Funktion preg_replace_callback_array() saubererer Code geschrieben werden. Vor PHP 7 musste für jeden regulären Ausdruck ein Callback ausgeführt werden, was dazu führte, dass die Callback-Funktion voller Verzweigungen sein musste.

Nun können Callbacks für jeden regulären Ausdruck registriert werden, indem ein assoziatives Array verwendet wird, bei dem die regulären Ausdrücke die Schlüssel sind, und die Callback-Funktionen deren Werte.

CSPRNG-Funktionen

Zwei neue Funktionen wurden hinzugefügt, um plattformübergreifend kryptographisch sichere Ganzzahlen und Zeichenketten zu erzeugen: random_bytes() und random_int().

list() kann nun immer Objekte entpacken, die ArrayAccess implementieren

Zuvor war nicht gewährleistet, dass list() bei Objekten, die ArrayAccess implementieren, korrekt funktioniert. Dies wurde nun behoben.

Andere Features

  • Es wurde die Möglichkeit hinzugefügt, beim Klonen auf Klassenelemente zuzugreifen, z. B. (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


Veraltete Features in PHP 7.0.x

Konstruktoren im Stil von PHP 4

Konstruktoren im Stil von PHP 4 (Methoden, die den gleichen Namen haben wie die Klasse, in der sie definiert sind) sind veraltet und werden in Zukunft entfernt. Wenn in einer Klasse nur dieser Typ von Konstruktor definiert ist, löst PHP 7 ein E_DEPRECATED aus. Klassen, die die Methode __construct() implementieren, sind davon nicht betroffen.

<?php
class foo {
function foo() {
echo 'Ich bin der Konstruktor';
}
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Statische Aufrufe nicht-statischer Methoden

Statische Aufrufe von Methoden, die nicht als static deklariert sind, sind veraltet und werden in der Zukunft möglicherweise entfernt.

<?php
class foo {
function bar() {
echo 'Ich bin nicht statisch!';
}
}

foo::bar();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
Ich bin nicht statisch!

Die Option salt von password_hash()

Bei der Funktion password_hash() ist die Option salt veraltet, um Entwickler daran zu hindern, ihr eigenes (normalerweise unsicheres) salt zu erzeugen. Wenn kein eigenes salt angegeben wird, generiert die Funktion selbst ein kryptographisch sicheres salt. Es ist daher nicht mehr nötig, selbst ein salt zu erzeugen.

Die SSL-Kontextoption capture_session_meta

Die SSL-Kontextoption capture_session_meta ist veraltet. SSL-Metadaten sind nun über die Funktion stream_get_meta_data() verfügbar.

LDAP

Die folgende Funktion ist veraltet:

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


Geänderte Funktionen

PHP-Kern

  • debug_zval_dump() Gibt nun "int" statt "long" und "float" statt "double" aus.
  • dirname() nimmt nun optional einen zweiten Parameter depth entgegen, womit der Name des Verzeichnisses, dass depth Stufen oberhalb des aktuellen liegt.
  • getrusage() wird nun auf Windows unterstützt.
  • Die mktime() und gmmktime() Funktionen akzeptieren den Parameter is_dst nicht mehr.
  • preg_replace() Funktion unterstützt den Modifier "\e" (PREG_REPLACE_EVAL) nicht mehr. Stattdessen sollte preg_replace_callback() verwendet werden.
  • setlocale() Funktion akzeptiert keine Zeichenketten mehr, die dem Parameter category übergeben werden. Stattdessen muss eine der LC_* Konstanten verwendet werden.
  • Die exec(), system() und passthru() Funktionen haben nun einen Nullbyte-Schutz.
  • shmop_open() gibt nun resource statt int zurück,
die den Funktionen shmop_size(),
shmop_write(), shmop_read(),
shmop_close() und shmop_delete() zu übergeben ist.
  • substr() und iconv_substr() geben eine leere Zeichenkette zurück, wenn start gleich der Länge der Zeichenkette entspricht.
  • xml_parser_free() ist nicht länger ausreichend, um die Parser-Ressource freizugeben, wenn sie ein Objekt referenziert und dieses Objekt jene Parser-Ressource referenziert. In diesem Fall ist es notwendig zusätzlich den Parser zu löschen (z.B. per unset()).

User Contributed Notes

There are no user contributed notes for this page.


Neue Funktionen

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Fehlerbehandlung und Protokollierung

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

PHP-Optionen/Info

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Zlib-Komprimierung

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


Neue Klassen und Interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Sessionbehandlung

  • SessionUpdateTimestampHandlerInterface

Ausnahmebehandlung

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


Neue globale Konstanten

Vordefinierte Core-Konstanten

  • PHP_INT_MIN

GD

  • IMG_WEBP (von PHP 7.0.10 an)

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.


Änderungen in SAPI-Modulen

FPM

Unqualifizierte listen-Ports lauschen nun sowohl auf IPv4 als auch auf IPv6

In PHP 5 führte eine listen-Direktive mit nur einer Portnummer dazu, dass auf allen Schnittstellen gelauscht wurde, aber nur auf IPv4. PHP 7 akzeptiert Anfragen nun sowohl über IPv4 als auch über IPv6.

Dies hat keine Auswirkungen auf Direktiven, die bestimmte IP-Adressen enthalten; diese lauschen weiterhin nur auf diese Adresse und dieses Protokoll.

User Contributed Notes

There are no user contributed notes for this page.


Entfernte Erweiterungen und SAPIs

Entfernte Erweiterungen

  • ereg
  • mssql
  • mysql
  • sybase_ct

Entfernte SAPIs

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


Sonstige Änderungen

Lockerung der Beschränkungen für reservierte Wörter

Global reservierte Wörter sind nun innerhalb von Klassen, Schnittstellen und Traits als Namen für Eigenschaften, Konstanten und Methoden erlaubt. Dadurch werden Probleme mit der Abwärtskompatibilität verringert, wenn neue Schlüsselwörter eingeführt werden, und Einschränkungen bei der Namensgebung für APIs vermieden.

Dies ist besonders nützlich, um interne DSLs mit "sprechenden" Schnittstellen (Fluent Interfaces) zu erstellen:

<?php
// 'new', 'private' und 'for' waren bisher nicht nutzbar.
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

Die einzige Einschränkung dabei ist, dass das Schlüsselwort class immer noch nicht als Name für eine Konstante verwendet werden kann, da es sonst zu einem Konflikt mit der Syntax zur Auflösung von Klassennamen (ClassName::class) kommen würde.

Die Warnung bei date.timezone wurde entfernt

Bisher wurde eine Warnung ausgegeben, wenn die INI-Einstellung date.timezone nicht vor der Verwendung von datums- oder zeitbasierten Funktionen gesetzt wurde. Nun wurde diese Warnung entfernt (wobei die Standardeinstellung für date.timezone immer noch UTC ist).

User Contributed Notes

There are no user contributed notes for this page.


Migration von PHP 5.5.x auf PHP 5.6.x

Inhaltsverzeichnis

  • Nicht abwärtskompatible Änderungen
  • Neue Features
  • Missbilligte Features in PHP 5.6.x
  • Geänderte Funktionen
  • Neue Funktionen
  • OpenSSL Änderungen in PHP 5.6.x
  • Sonstige Änderungen bei Extensions
  • Neue globale Konstanten

Die meisten Verbesserungen in PHP 5.6.x haben keinen Einfluss auf bereits bestehenden Code. Es gibt einige wenige Inkompatibilitäten und neue Features, die berücksichtigt werden sollten, und Code sollte getestet werden, bevor die PHP-Version in produktiven Umgebungen geändert wird.

User Contributed Notes

There are no user contributed notes for this page.


Nicht abwärtskompatible Änderungen

Obwohl der meiste bestehende PHP 5 Code ohne Änderungen funktionieren sollte, sind ein paar Änderungen zu beachten, die nicht abwärtskompatibel sind:

Array-Schlüssel werden nicht überschrieben, wenn ein Array mittels Array-Literal als Eigenschaft einer Klasse definiert wird

Bisher konnten Elemente von Arrays, welche als Klasseneigenschaften mit expliziten und impliziten Schlüsseln definiert waren, überschrieben werden, wenn ein expliziter Schlüssel gleich mit einem sequenziellen impliziten Schlüssel war.

<?php
class C {
const ONE = 1;
public $array = [
self::ONE => 'foo',
'bar',
'quux',
];
}

var_dump((new C)->array);
?>

Das oben gezeigte Beispiel erzeugt mit PHP 5.5 folgende Ausgabe:

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

Das oben gezeigte Beispiel erzeugt mit PHP 5.6 folgende Ausgabe:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

Strenge von json_decode()

json_decode() weist nun nicht vollständig in Kleinbuchstaben geschriebene Varianten von true, false und null gemäß der JSON-Spezifikation zurück, und setzt json_last_error() dementsprechend. Bisher wurden auch Eingaben, die nur aus einem dieser Werte bestanden, mit Großbuchstaben akzeptiert.

Diese Änderung hat nur Einfluss auf Fälle in denen ungültiges JSON an json_decode() übergeben wurde. Gültiges JSON ist davon nicht betroffen und wird weiterhin normal verarbeitet.

Stream Wrapper verifizieren nun standardmäßig Zertifikate und Hostnamen bei Verwendung von SSL/TLS

Alle verschlüsselten Clientstreams verifizieren nun standardmäßig den Kommunikationspartner. Standardmäßig wird dafür das Standard-CA-Bundle von OpenSSL zur Verifikation des Peer-Zertifikates herangezogen. In den meisten Fällen sind keine Änderungen notwendig, um mit Servern mit gültigen SSL-Zertifikaten zu kommunizieren, da Distributoren üblicherweise OpenSSL mit vertrauenswürdigen CA-Bundles konfigurieren.

Das Standard-CA-Bundle kann global durch eine Änderung der konfigurationseinstellungen openssl.cafile oder openssl.capath überschrieben werden, oder für einzelne Requests durch die Verwendung der Kontextoptionen cafile oder capath.

Obwohl dies generell nicht empfehlenswert ist, kann die Verifikation der Peer-Zertifikate für einzelne Requests ausgeschaltet werden, indem die Kontextoption verify_peer auf false gesetzt wird. Die Verifikation des Peer-Namen kann durch das Setzen von verify_peer_name verify_peer_name auf false ausgeschaltet werden.

GMP-Ressourcen sind nun Objekte

GMP-Ressourcen sind nun Objekte. Die funktionale API der GMP-Erweiterung hat sich nicht geändert und Code sollte ohne Änderungen funktionieren, es sei denn dieser prüft explizit auf eine Ressource mittels is_resource() oder Ähnlichem.

Mcrypt-Funktionen benötigen nun gültige Schlüssel und IVs

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() und mcrypt_ofb() akzeptieren nicht länger Schlüssel oder IVs mit falscher Länge, und Blockschlüssel, die IVs benötigen, schlagen nun fehl, wenn kein IV übergeben wurde.

cURL Datei-Uploads

Uploads, die die @file Syntax verwenden, erfordern nun, dass CURLOPT_SAFE_UPLOAD auf false gesetzt ist. Statt dessen sollte CURLFile verwendet werden.

User Contributed Notes

There are no user contributed notes for this page.


Neue Features

Konstante Ausdrücke

Es ist nun möglich einen skalaren Ausdruck mit numerischen oder String-Literalen und/oder Konstanten in Kontexten zu verwenden, in denen PHP bisher einen statischen Wert erwartete, beispielsweise Deklarationen von Konstanten und Eigenschaften und Standardwerte von Funktionsparametern.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'Der Wert von THREE ist '.self::THREE;

public function f($a = ONE + self::THREE) {
return $a;
}
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

4
Der Wert von THREE ist 3

Es ist nun auch möglich, ein konstantes Array mit dem Schlüsselwort const zu definieren:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

a

Variadische Funktionen mit ...

Variadische Funktionen können nun mit dem Operator ... implementiert werden, anstatt func_get_args() zu verwenden.

<?php
function f($req, $opt = null, ...$params) {
// $params ist ein Array welches die übrigen Parameter enthält.
printf('$req: %d; $opt: %d; Anzahl Parameter: %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);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

$req: 1; $opt: 0; Anzahl Parameter: 0
$req: 1; $opt: 2; Anzahl Parameter: 0
$req: 1; $opt: 2; Anzahl Parameter: 1
$req: 1; $opt: 2; Anzahl Parameter: 2
$req: 1; $opt: 2; Anzahl Parameter: 3

Entpacken von Argumenten mit ...

Arrays und Traversable-Objekte können in eine Liste von Parametern entpackt werden, indem der ... Operator verwendet wird. Dies ist in anderen Sprachen, wie beispielsweise Ruby, auch als Splat-Operator bekannt.

<?php
function add($a, $b, $c) {
return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

6

Potenzieren mit **

Der rechtsassoziative Operator ** zum Potenzieren wurde gemeinsam mit dem abkürzenden Zuweisungsoperator **= hinzugefügt.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function und use const

Der Operator use wurde um das Importieren von Funktionen und Konstanten zusätzlich zu Klassen erweitert. Dies kann jeweils entsprechend durch die Konstrukte use function bzw. use const erreicht werden.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

42
Name\Space\f

phpdbg

PHP enthält nun einen interaktiven Debugger namens phpdbg, welcher als SAPI-Modul umgesetzt wurde. Weitere Informationen findet man in der phpdbg-Dokumentation.

Standardzeichencodierung

default_charset wird nun als Standardzeichenkodierung für die Funktionen htmlentities(), html_entity_decode() und htmlspecialchars() herangezogen. Falls die (nun missbilligten) Einstellungen für die Zeichenkodierung von iconv und mbstring gesetzt sind, haben diese Vorrang gegenüber default_charset für die iconv beziehungsweise mbstring Funktionen.

Die Standardeinstellung hierfür ist UTF-8.

php://input ist wiederverwendbar

php://input kann nun so oft wie nötig geöffnet und ausgelesen werden. Diese Änderung hat auch zu einer erheblichen Reduktion im Speicherverbrauch bei der Verarbeitung von POST-Daten geführt.

Große Dateiuploads

Es werden nun auch Dateien mit einer Größe von mehr als zwei Gigabyte angenommen.

GMP unterstützt Operatorüberladung

GMP-Objekte unterstützen nun Operatorüberladung und das Casten zu skalaren Typen. Dies erlaubt besser lesbaren Code bei Verwendung von 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;
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

59
59
59

hash_equals() für Stringvergleiche mit Schutz gegen Rechenzeitangriffe

Die Funktion hash_equals() wurde hinzugefügt, welche zwei Zeichenketten in konstanter Zeit vergleicht. Dies sollte verwendet werden, um Rechenzeitangriffe zu verhindern, beispielsweise wenn crypt()-Passworthashes geprüft werden (unter der Annahme, dass password_hash() und password_verify() nicht verwendet werden können, welche gegen Rechenzeitangriffe nicht anfällig sind).

<?php
$expected = crypt('12345', '$2a$07$benutzeeinenlangenstringalssalt$');
$correct = crypt('12345', '$2a$07$benutzeeinenlangenstringalssalt$');
$incorrect = crypt('1234', '$2a$07$benutzeeinenlangenstringalssalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(true)
bool(false)

__debugInfo()

Die magische Methode __debugInfo() wurde hinzugefügt, welche es Objekten erlaubt, die Eigenschaften und Werte zu bestimmen, welche bei Verwendung von var_dump() ausgegeben werden.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

gost-crypto Hashalgorithmus

Der Hashalgorithmus gost-crypto wurde hinzugefügt. Dieser implementiert die GOST-Hash-Funktion unter Verwendung der CryptoPro S-box Tabellen wie in » RFC 4357, Abschnitt 11.2 spezifiziert.

SSL/TLS-Verbesserungen

Eine große Zahl an Verbesserungen an der SSL/TLS-Unterstützung wurden in PHP 5.6 vorgenommen. Dies umfasst die standardmäßige Aktivierung von Peer-Verifikation, Unterstützung von Zertifikat-Fingerabdrucksprüfung, Verhinderung von TLS-Renegotiation-Attacken und viele neue SSL Kontextoptionen, welche eine detailliertere Kontrolle über Protokoll- und Verifikationseinstellungen bei Verwendung von verschlüsselten Streams erlauben.

Diese Änderungen werden im Abschnitt OpenSSL Änderungen in PHP 5.6.x dieser Migrationsanleitung detaillierter beschrieben.

Unterstützung für pgsql async

Die Extension pgsql unterstützt nun asynchrone Verbindungen und Abfragen, womit nicht blockierendes Verhalten bei der Interaktion mit PostgreSQL-Datenbanken ermöglicht wird. Asynchrone Verbindungen können mittels der Konstante PGSQL_CONNECT_ASYNC aufgebaut werden, und die neuen Funktionen pg_connect_poll(), pg_socket(), pg_consume_input() und pg_flush() behandeln asynchrone Verbindungen und Abfragen.

User Contributed Notes

There are no user contributed notes for this page.


Missbilligte Features in PHP 5.6.x

Aufrufe aus inkompatiblem Kontext

Methodenaufrufe aus inkompatiblem Kontext sind nun missbilligt, und rufen einen Fehler der Stufe E_DEPRECATED hervor anstelle von E_STRICT. Die Unterstützung für derartige Aufrufe wird in einer zukünftigen Version von PHP entfernt.

Ein Beispiel für einen derartigen Aufruf:

<?php
class A {
function f() { echo get_class($this); }
}

class B {
function f() { A::f(); }
}

(new B)->f();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

always_populate_raw_post_data ruft nun einen Fehler der Stufe E_DEPRECATED hervor, wenn $HTTP_RAW_POST_DATA befüllt wird. Neuer Code sollte php://input anstelle von $HTTP_RAW_POST_DATA verwenden, welches in einer zukünftigen Version entfernt wird. Es kann bereits jetzt das neue Verhalten (bei dem $HTTP_RAW_POST_DATA nie befüllt und damit kein E_DEPRECATED-Fehler hervorgerufen wird) verwendet werden, wenn always_populate_raw_post_data auf -1 gestellt wird.

Einstellungen zur Zeichenkodierung von iconv und mbstring

Die Konfigurationseinstellungen für die Zeichenkodierung der Funktionen iconv und mbstring werden nun zugunsten von default_charset als missbilligt eingestuft. Die missbilligten Optionen sind:

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


Geänderte Funktionen

PHP Core

  • crypt() ruft nun einen Fehler der Stufe E_NOTICE hervor, wenn der Parameter salt ausgelassen wird.
  • substr_compare() akzeptiert nun auch 0 als Wert für den Parameter length.
  • unserialize() schlägt nun fehl, wenn serialisierte Daten übergeben werden, welche so manipuliert wurden, dass ein Objekt erzeugt werden soll ohne dessen Konstruktor aufzurufen.

cURL

  • Uploads mittels der @file-Syntax werden nun nur noch unterstützt, wenn die Option CURLOPT_SAFE_UPLOAD auf false gestellt wird. Es sollte stattdessen CURLFile verwendet werden.

Mcrypt

  • Der Parameter source von mcrypt_create_iv() hat nun einen Standardwert von MCRYPT_DEV_URANDOM anstelle von MCRYPT_DEV_RANDOM.

OpenSSL

  • Der Parameter crypto_type von stream_socket_enable_crypto() kann nun optional sein, wenn der SSL-Kontext des Streams die neue Option crypto_type enthält.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() und pg_delete() sind nicht länger experimentell.
  • pg_send_execute(), pg_send_prepare(), pg_send_query() und pg_send_query_params() blockieren nicht mehr bis die Schreiboperation der Abfrage abgeschlossen ist, wenn der zugrunde liegende Socket-Stream der Datenbankverbindung auf einen nicht blockierenden Modus eingestellt ist.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() erlaubt nun die Instanziierung von nicht-finalen internen Klassen.

XMLReader

  • XMLReader::getAttributeNs() und
XMLReader::getAttributeNo() geben nun,
wie XMLReader::getAttribute()
null zurück, wenn das Attribut nicht gefunden wurde.

User Contributed Notes

There are no user contributed notes for this page.


Neue Funktionen

Datum und Uhrzeit

  • 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 Änderungen in PHP 5.6.x

Streamwrapper verifizieren nun standardmäßig Zertifikate und Hostnamen bei Verwendung von SSL/TLS

Alle verschlüsselten Clientstreams verifizieren nun standardmäßig den Kommunikationspartner. Standardmäßig wird dafür das Standard-CA-Bundle von OpenSSL zur Verifikation des Peer-Zertifikates herangezogen. In den meisten Fällen sind keine Änderungen notwendig, um mit Servern mit gültigen SSL-Zertifikaten zu kommunizieren, da Distributoren üblicherweise OpenSSL mit vertrauenswürdigen CA-Bundles konfigurieren.

Das Standard-CA-Bundle kann global durch eine Änderung der konfigurationseinstellungen openssl.cafile oder openssl.capath überschrieben werden, oder für einzelne Requests durch die Verwendung der Kontextoptionen cafile oder capath.

Obwohl dies generell nicht empfehlenswert ist, kann die Verifikation der Peer-Zertifikate für einzelne Requests ausgeschaltet werden, indem die Kontextoption verify_peer auf false gesetzt wird. Die Verifikation des Peer-Namen kann durch das Setzen von verify_peer_name verify_peer_name auf false ausgeschaltet werden.

Fingerabdrücke von Zertifikaten

Es wurde Unterstützung für das Auslesen und Verifizieren von Fingerabdrücken von Zertifikaten hinzugefügt. openssl_x509_fingerprint() kam hinzu, um den Fingerabdruck aus X.509-Zertifikaten auszulesen und zwei neue SSL Streamkontext-Optionen wurden hinzugefügt: capture_peer_cert zum Auslesen des X.509- Zertifikats des Kommunikationspartners und peer_fingerprint zur Durchsetzung, dass das Zertifikat des Kommunikationspartners dem angegebenen Fingerabdruck entsprechen muss.

Aktualisierung der Standardchiffren

Die von PHP verwendeten Standardchiffren wurden auf eine sicherere Liste aktualisiert, basierend auf den » Mozilla Chiffreempfehlungen, mit zwei zusätzlichen Ausnahmen: anonyme Diffie-Hellman Chiffren und RC4.

Auf diese Liste kann mit der neuen Konstante OPENSSL_DEFAULT_STREAM_CIPHERS zugegriffen und (wie in früheren PHP-Versionen) durch das Setzen der Kontextoption ciphers übersteuert werden.

Komprimierung standardmäßig deaktiviert

Komprimierung von SSL/TLS wurde standardmäßig deaktiviert, um die CRIME-Attacke zu umgehen. PHP 5.4.13 fügte die Kontextoption disable_compression hinzu, um die Komprimierung zu deaktivieren. Dies ist nun standardmäßig auf true (d. h. Komprimierung deaktiviert) gesetzt.

Servern wird erlaubt, die Reihenfolge bevorzugter Chiffren festzulegen

Die SSL Kontextoption honor_cipher_order wurde hinzugefügt, um Servern von verschlüsselten Streams die Umgehung der BEAST-Schwachstelle zu ermöglichen, indem die Chiffren des Servers gegenüber denen des Clients bevorzugt werden.

Zugriff auf ausgehandeltes Protokoll und Chiffre

Auf das Protokoll und die Chiffre, die für einen verschlüsselten Stream ausgehandelt wurden, kann nun mittels stream_get_meta_data() oder stream_context_get_options() zugegriffen werden, wenn die SSL-Kontextoption capture_session_meta auf true gesetzt ist.

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

Neue Optionen für Perfect Forward Secrecy bei Servern für verschlüsselte Streams

Verschlüsselte Clientstreams unterstützen Perfect Forward Secrecy bereits, da dies üblicherweise vom Server kontrolliert wird. Es muss nichts zusätzlich unternommen werden, um PFS bei verschlüsselten PHP-Server-Streams zu aktivieren, die Zertifikate verwenden, welche Perfect Forward Secrecy unterstützen. Es wurden jedoch einige neue SSL-Kontextoptionen hinzugefügt, welche mehr Kontrolle über PFS erlauben und eventuell auftretende Kompatibilitätsprobleme behandeln.

ecdh_curve

Diese Option erlaubt die Auswahl einer spezifischen Kurve für ECDH-Chiffren. Falls nicht angegeben, wird prime256v1 verwendet.

dh_param

Pfad zu einer Datei, welche Parameter für den Diffie-Hellman-Schlüsselaustausch enthält, die beispielsweise durch folgenden Befehl erzeugt werden könnte:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

Ist dies auf true gesetzt, wird ein neues Schlüsselpaar erzeugt, wenn Diffie-Hellman-Parameter verwendet werden, wodurch sich die Forward Secrecy verbessert.

single_ecdh_use

Ist dies auf true gesetzt, wird immer ein neues Schlüsselpaar erzeugt, wenn ECDH-Chiffren ausgehandelt werden. Dies verbessert die Forward Secrecy.

SSL/TLS Versionsauswahl

Es ist nun möglich die spezifischen Versionen von SSL oder TLS mittels der SSL-Kontextoption crypto_method oder durch die Angabe eines spezifischen Transportes bei der Erzeugung des Streamwrappers auszuwählen (beispielsweise durch den Aufruf von stream_socket_client() oder stream_socket_server()).

Die SSL-Kontextoption crypto_method erwartet eine Bitmaske in der die erlaubten Protokolle aufgezählt sind. Der Parameter crypto_type von stream_socket_enable_crypto() verhält sich genauso.

Ausgewählte Protokollversionen und zugehörige Optionen
Protokoll(e) | Client-Flag | Server-Flag | Transport
Beliebige Version von TLS oder SSL | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Beliebige 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

// Voraussetzen von TLS 1.0 oder neuer bei Verwendung von
// file_get_contents():
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// TLS 1.1 oder 1.2 voraussetzen:
$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);

// Verbindung mittels tlsv1.2:// Stream-Socket-Transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() hinzugefügt

Die Funktion openssl_get_cert_locations() wurde hinzugefügt: Sie gibt den Standard-Ablageort aus, der von PHP bei der Suche von CA-Bundles verwendet wird.

<?php
var_dump(openssl_get_cert_locations());
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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-Unterstützung

Unterstützung für die Erzeugung, das Auslesen und das Verifizieren von Signed Public Key And Challenges wurde (SPKAC) wurde hinzugefügt. Die Funktionen openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge() und openssl_spki_export() wurden hinzugefügt, welche die durch ein KeyGen HTML5-Element erzeugten SPKACs erzeugen, verifizieren oder den PEM Public Key und zugehörige Challenge exportieren.

openssl_spki_new

Erzeugt ein neues SPKAC mit einem privaten Schlüssel, Challenge-String und Hashalgorithmus.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifiziert ein angegebenes 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

Exportiert eine zugehörige Challenge eines angegebenen 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;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

challenge string
openssl_spki_export

Exportiert den PEM-formatierten öffentlichen RSA-Schlüssel aus einer SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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


Sonstige Änderungen bei Extensions

cURL

Eine Reihe von als veraltet angesehenen Konstanten in der cURL-Bibliothek wurden nun entfernt:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Unterstützung von impliziten Resultsets für Oracle Database 12c wurde durch die neue Funktion oci_get_implicit_resultset() hinzugefügt.
  • Die Verwendung von oci_execute($s, OCI_NO_AUTO_COMMIT) für ein SELECT ruft nicht mehr unnötigerweise ein internes ROLLBACK beim Schließen der Verbindung hervor.
  • DTrace-Probes wurden hinzugefügt, konfiguriert durch die Konfigurations-Option --enable-dtrace.
  • oci_internal_debug() tut nichts mehr.
  • Das Ausgabeformat von phpinfo() im Bezug auf OCI8 hat sich geändert.

Zip

Eine Konfigurations-Option --with-libzip wurde aufgenommen, welche die Verwendung einer vom System bereitgestellten libzip-Installation ermöglicht. Die libzip-Version 0.11 ist notwendig, 0.11.2 oder neuer werden empfohlen.

MySQLi

Die neue Option mysqli.rollback_on_cached_plink wurde hinzugefügt, die das Rollback-Verhalten persistenter Verbindungen steuert.

User Contributed Notes

There are no user contributed notes for this page.


Neue globale Konstanten

GD

  • IMG_WEBP (von PHP 5.6.25 an)

LDAP

  • LDAP_ESCAPE_DN
  • LDAP_ESCAPE_FILTER

OpenSSL

  • OPENSSL_DEFAULT_STREAM_CIPHERS
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

PostgreSQL

  • PGSQL_CONNECT_ASYNC
  • PGSQL_CONNECTION_AUTH_OK
  • PGSQL_CONNECTION_AWAITING_RESPONSE
  • PGSQL_CONNECTION_MADE
  • PGSQL_CONNECTION_SETENV
  • PGSQL_CONNECTION_SSL_STARTUP
  • PGSQL_CONNECTION_STARTED
  • PGSQL_DML_ESCAPE
  • PGSQL_POLLING_ACTIVE
  • PGSQL_POLLING_FAILED
  • PGSQL_POLLING_OK
  • PGSQL_POLLING_READING
  • PGSQL_POLLING_WRITING

User Contributed Notes

There are no user contributed notes for this page.


PHP Debugging

Inhaltsverzeichnis

  • Über Debugging in 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!


Über Debugging in PHP

PHP enthält einen einfachen interaktiven Debugger für die Kommandozeile, phpdbg.

Die meisten IDEs unterstützen » Xdebug, ein kostenloses Debug-Tool, mit dem PHP-Anwendungen in einzelnen Schritten auf Fehler untersucht werden können (Single Step Debugging).

User Contributed Notes

There are no user contributed notes for this page.


Konfigurationsoptionen

Inhaltsverzeichnis

  • Liste der Kern-Konfigurationsoptionen

User Contributed Notes

There are no user contributed notes for this page.


Liste der Kern-Konfigurationsoptionen

Nachfolgend finden Sie eine Teilliste der Konfigurationsoptionen, die von den PHP configure Skripten beim Kompilieren in Unix-ähnlichen Umgebungen verwendet werden. Die meisten Konfigurationsoptionen sind in den entsprechenden Referenzseiten der Erweiterungen aufgeführt und nicht hier. Für eine vollständige aktuelle Liste der Konfigurationsoptionen, führen Sie ./configure --help in Ihrem PHP-Quellcode-Verzeichnis aus, nachdem Sie autoconf ausgeführt haben (siehe auch den Installationskapitel). Vielleicht interessieren Sie sich auch für die » GNU configure Dokumentation für Informationen über zusätzliche configure Optionen wie --prefix=PREFIX.

Hinweis:

Diese werden nur zur Kompilierungszeit verwendet. Wenn sie die Laufzeitkonfiguration von PHP ändern wollen, lesen Sie bitte das Kapitel über Laufzeitkonfiguration.

  • Verschiedenes
  • PHP-Verhalten
  • Server

PHP-Optionen konfigurieren

Verschiedene Optionen

--enable-debug

Kompilieren mit Debugging-Symbolen.

--with-layout=TYP

Legt fest, wie die installierten Dateien angeordnet werden sollen. Typ ist PHP (Standard) oder GNU. Wenn die Manpages unter PREFIX installiert werden (Standard), sollte der GNU-Stil gewählt werden, damit sie im Suchpfad des Programms manpath gefunden werden können.

--with-pear=DIR

Installiert PEAR in DIR (Voreinstellung PREFIX/lib/php).

--without-pear

Installiert PEAR nicht.

--enable-sigchild

Aktiviert den PHP-eigenen SIGCHLD-Handler.

--disable-rpath

Deaktiviert die Übergabe zusätzlicher Suchpfade der Laufzeitbibliothek.

--enable-libgcc

Aktiviert die explizite Verlinkung gegen libgcc.

--enable-php-streams

Experimentelle PHP-Streams einbinden. Verwenden Sie dies nicht, es sei denn, Sie testen den Code!

--with-zlib-dir[=DIR]

Definiert den Speicherort des zlib-Installationsverzeichnisses.

--with-tsrm-pthreads

POSIX-Threads verwenden (Voreinstellung).

--enable-shared[=PKGS]

Gemeinsame Bibliotheken erstellen [Voreinstellung=ja].

--enable-static[=PKGS]

Erstellt statische Bibliotheken [Voreinstellung=ja].

--enable-fast-install[=PKGS]

Optimieren für schnelle Installation [Voreinstellung=ja].

--with-gnu-ld

Annehmen, dass der C-Compiler GNU ld verwendet [Voreinstellung=nein].

--disable-libtool-lock

Sperren vermeiden (könnte parallele Builds beschädigen).

--with-pic

Es wird versucht, nur PIC/Nicht-PIC-Objekte zu verwenden [Voreinstellung=beide verwenden].

--enable-versioning

Nur erforderliche Symbole exportieren. Siehe INSTALL für weitere Informationen.

PHP-Optionen

--enable-maintainer-mode

Aktiviert Makefile-Regeln und Abhängigkeiten, die für den gewöhnlichen Anwender nicht nützlich (und manchmal auch verwirrend) sind.

--with-config-file-path=PATH

Setzt den Pfad, in dem nach der php.ini gesucht wird; der Vorgabewert ist PREFIX/lib.

--disable-short-tags

Die Tag-Kurzform <? wird standardmäßig deaktiviert.

--with-libdir

Gibt das Verzeichnis an, in dem die für die Kompilierung von PHP erforderlichen Bibliotheken auf einem Unix-Sytem zu finden sind. Für 64-bit Systeme ist es erforderlich, dieses Argument wie folgt auf das lib64 zu setzen: --with-libdir=lib64.

--enable-zts

Aktiviert die Thread-Sicherheit. Vor PHP 8.0.0 hieß die Option auf Nicht-Windows-Systemen --enable-maintainer-zts.

SAPI-Optionen

Die folgende Liste enthält die für PHP verfügbaren SAPIs (Server Application Programming Interfaces).

--with-apxs[=FILE]

Erstellt ein dynamisches (shared) Modul für Apache. FILE ist der optionale Pfadname zum apxs-Tool von Apache; die Voreinstellung ist apxs. Es ist darauf zu achten, dass die Version von apxs angegeben wird, die tatsächlich auf dem System installiert ist, und NICHT die aus den Apache-Quellen.

--with-apache[=DIR]

Erstellt ein statisches Modul für Apache. DIR ist das oberste Verzeichnis der Apache-Installation; die Voreinstellung ist /usr/local/apache.

--with-mod_charset

Aktiviert die Umkodierungstabellen für das Modul mod_charset (für die russische Apache-Version).

--with-apxs2[=FILE]

Erstellt ein dynamisches Modul für Apache 2.0. FILE ist der optionale Pfadname zum apxs-Tool von Apache; die Voreinstellung ist apxs.

--disable-cli

Deaktiviert die Erstellung der CLI-Version von PHP (dies impliziert --without-pear). Weitere Informationen sind im Abschnitt über die Nutzung von PHP auf der Kommandozeile zu finden.

--enable-phpdbg

Aktiviert die Unterstützung für das SAPI-Modul des interaktiven Debuggers phpdbg.

--enable-embed[=TYPE]

Aktiviert die Erstellung der integrierten SAPI-Bibliothek. TYPE ist entweder shared oder static; die Voreinstellung ist shared.

--with-servlet[=DIR]

Fügt die Unterstützung von Servlets hinzu. DIR ist das Basisverzeichnis der JSDK-Installation. Für diese SAPI muss die Java-Erweiterung als Shared Library kompiliert werden.

--disable-cgi

Deaktiviert die Erstellung der CGI-Version von PHP.

Dieser Parameter aktiviert auch 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 Direktiven

Inhaltsverzeichnis

  • Liste der php.ini-Direktiven
  • Liste der php.ini-Abschnitte
  • Beschreibung der php.ini-Direktiven des Sprachkerns

User Contributed Notes

There are no user contributed notes for this page.


Liste der php.ini-Direktiven

Diese Liste enthält die php.ini-Direktiven, die zur Konfiguration von PHP genutzt werden können.

Die "Veränderbar"-Spalte gibt an, wann und wo die Direktive geändert werden kann. Siehe Liste der möglichen Modi für deren Definitionen.

Konfigurationsoptionen
Name | Standard | Veränderbar | Changelog
allow_url_fopen | "1" | INI_SYSTEM |
allow_url_include | "0" | INI_SYSTEM | Missbilligt von PHP 7.4.0 an.
arg_separator.input | "&" | INI_PERDIR |
arg_separator.output | "&" | INI_ALL |
assert.active | "1" | INI_ALL |
assert.bail | "0" | INI_ALL |
assert.callback | null | INI_ALL |
assert.exception | "0" | INI_ALL |
assert.quiet_eval | "0" | INI_ALL | Seit PHP 8.0.0 entfernt
assert.warning | "1" | INI_ALL |
auto_append_file | null | INI_PERDIR |
auto_detect_line_endings | "0" | INI_ALL |
auto_globals_jit | "1" | INI_PERDIR |
auto_prepend_file | null | INI_PERDIR |
bcmath.scale | "0" | INI_ALL |
browscap | null | INI_SYSTEM |
cgi.check_shebang_line | "1" | INI_SYSTEM |
cgi.discard_path | "0" | INI_SYSTEM |
cgi.fix_pathinfo | "1" | INI_SYSTEM |
cgi.force_redirect | "1" | INI_SYSTEM |
cgi.nph | "0" | INI_ALL |
cgi.redirect_status_env | null | INI_SYSTEM |
cgi.rfc2616_headers | "0" | INI_ALL |
child_terminate | "0" | INI_ALL |
cli.pager | "" | INI_ALL |
cli.prompt | "\\b \\> " | INI_ALL |
cli_server.color | "0" | INI_ALL |
com.allow_dcom | "0" | INI_SYSTEM |
com.autoregister_typelib | "0" | INI_ALL |
com.autoregister_verbose | "0" | INI_ALL |
com.autoregister_casesensitive | "1" | INI_ALL |
com.code_page | "" | INI_ALL |
com.dotnet_version | "" | INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | INI_SYSTEM |
curl.cainfo | NULL | INI_SYSTEM |
date.default_latitude | "31.7667" | INI_ALL |
date.default_longitude | "35.2333" | INI_ALL |
date.sunrise_zenith | "90.833333" | INI_ALL | Vor PHP 8.0.0 war der Standardwert "90.583333"
date.sunset_zenith | "90.833333" | INI_ALL | Vor PHP 8.0.0 war der Standardwert "90.583333"
date.timezone | "UTC" | INI_ALL | Seit PHP 8.2 wird eine Warnung ausgegeben, wenn dies auf einen ungültigen Wert oder eine leere Zeichenkette gesetzt wird.
dba.default_handler | DBA_DEFAULT | INI_ALL |
default_charset | "UTF-8" | INI_ALL |
input_encoding | "" | INI_ALL |
output_encoding | "" | INI_ALL |
internal_encoding | "" | INI_ALL |
default_mimetype | "text/html" | INI_ALL |
default_socket_timeout | "60" | INI_ALL |
disable_classes | "" | Nur php.ini |
disable_functions | "" | Nur php.ini |
display_errors | "1" | INI_ALL |
display_startup_errors | "1" | INI_ALL | Vor PHP 8.0.0 war der Standardwert "0".
docref_ext | "" | INI_ALL |
docref_root | "" | INI_ALL |
doc_root | null | INI_SYSTEM |
enable_dl | "1" | INI_SYSTEM | Dieses veraltete Feature wird in der Zukunft sicherlich entfernt.
enable_post_data_reading | "On" | INI_PERDIR |
engine | "1" | INI_ALL |
error_append_string | null | INI_ALL |
error_log | null | INI_ALL |
error_log_mode | 0o644 | INI_ALL | Verfügbar ab PHP 8.2.0
error_prepend_string | null | INI_ALL |
error_reporting | null | INI_ALL |
exif.encode_unicode | "ISO-8859-15" | INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | INI_ALL |
exif.encode_jis | "" | INI_ALL |
exif.decode_jis_motorola | "JIS" | INI_ALL |
exif.decode_jis_intel | "JIS" | INI_ALL |
exit_on_timeout | "" | INI_ALL |
expect.timeout | "10" | INI_ALL |
expect.loguser | "1" | INI_ALL |
expect.logfile | "" | INI_ALL |
expect.match_max | "" | INI_ALL |
expose_php | "1" | Nur php.ini |
extension | null | Nur php.ini |
extension_dir | "/path/to/php" | INI_SYSTEM |
fastcgi.impersonate | "0" | INI_SYSTEM |
fastcgi.logging | "1" | INI_SYSTEM |
file_uploads | "1" | INI_SYSTEM |
filter.default | "unsafe_raw" | INI_PERDIR | Seit PHP 8.1.0 veraltet.
filter.default_flags | NULL | INI_PERDIR |
from | "" | INI_ALL |
gd.jpeg_ignore_warning | "1" | INI_ALL |
geoip.custom_directory | "" | INI_ALL |
hard_timeout | "2" | INI_SYSTEM | Verfügbar seit PHP 7.1.0.
highlight.comment | "#FF8000" | INI_ALL |
highlight.default | "#0000BB" | INI_ALL |
highlight.html | "#000000" | INI_ALL |
highlight.keyword | "#007700" | INI_ALL |
highlight.string | "#DD0000" | INI_ALL |
html_errors | "1" | INI_ALL |
ibase.allow_persistent | "1" | INI_SYSTEM |
ibase.max_persistent | "-1" | INI_SYSTEM |
ibase.max_links | "-1" | INI_SYSTEM |
ibase.default_db | NULL | INI_SYSTEM |
ibase.default_user | NULL | INI_ALL |
ibase.default_password | NULL | INI_ALL |
ibase.default_charset | NULL | INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | INI_ALL |
ibase.dateformat | "%Y-%m-%d" | INI_ALL |
ibase.timeformat | "%H:%M:%S" | INI_ALL |
ibm_db2.binmode | "1" | INI_ALL |
ibm_db2.i5_all_pconnect | "0" | INI_SYSTEM | Available as of ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | INI_SYSTEM | Available as of ibm_db2 1.4.9.
ibm_db2.i5_blank_userid | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_char_trim | "0" | INI_SYSTEM | Available as of ibm_db2 2.1.0.
ibm_db2.i5_dbcs_alloc | "0" | INI_SYSTEM | Available as of ibm_db2 1.5.0.
ibm_db2.i5_guard_profile | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_ignore_userid | "0" | INI_SYSTEM | Available as of ibm_db2 1.8.0.
ibm_db2.i5_job_sort | "0" | INI_SYSTEM | Available as of ibm_db2 1.8.4.
ibm_db2.i5_log_verbose | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_max_pconnect | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_override_ccsid | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_servermode_subsystem | NULL | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.i5_sys_naming | "0" | INI_SYSTEM | Available as of ibm_db2 1.9.7.
ibm_db2.instance_name | NULL | INI_SYSTEM | Available as of ibm_db2 1.0.2.
iconv.input_encoding | "" | INI_ALL | Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | INI_ALL | Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | INI_ALL | Deprecated in PHP 5.6.0.
ignore_repeated_errors | "0" | INI_ALL |
ignore_repeated_source | "0" | INI_ALL |
ignore_user_abort | "0" | INI_ALL |
implicit_flush | "0" | INI_ALL |
include_path | ".:/path/to/php/pear" | INI_ALL |
intl.default_locale |  | INI_ALL |
intl.error_level | 0 | INI_ALL |
intl.use_exceptions | 0 | INI_ALL | Available since PECL 3.0.0a1
last_modified | "0" | INI_ALL |
ldap.max_links | "-1" | INI_SYSTEM |
log_errors | "0" | INI_ALL |
log_errors_max_len | "1024" | INI_ALL |
mail.add_x_header | "0" | INI_PERDIR |
mail.force_extra_parameters | null | Nur php.ini |
mail.log | "" | INI_PERDIR |
max_execution_time | "30" | INI_ALL |
max_input_nesting_level | "64" | INI_PERDIR |
max_input_vars | 1000 | INI_PERDIR |
max_input_time | "-1" | INI_PERDIR |
mbstring.language | "neutral" | INI_ALL |
mbstring.detect_order | NULL | INI_ALL |
mbstring.http_input | "pass" | INI_ALL | Deprecated
mbstring.http_output | "pass" | INI_ALL | Deprecated
mbstring.internal_encoding | NULL | INI_ALL | Deprecated
mbstring.substitute_character | NULL | INI_ALL |
mbstring.func_overload | "0" | INI_SYSTEM | Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation | "0" | INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | INI_ALL |
mbstring.strict_detection | "0" | INI_ALL |
mbstring.regex_retry_limit | "1000000" | INI_ALL | Available as of PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | INI_ALL | Available as of PHP 7.3.5.
mcrypt.algorithms_dir | null | INI_ALL |
mcrypt.modes_dir | null | INI_ALL |
memcache.allow_failover | "1" | INI_ALL | Verfügbar seit Memcache 2.0.2.
memcache.max_failover_attempts | "20" | INI_ALL | Verfügbar seit Memcache 2.1.0.
memcache.chunk_size | "8192" | INI_ALL | Verfügbar seit Memcache 2.0.2.
memcache.default_port | "11211" | INI_ALL | Verfügbar seit Memcache 2.0.2.
memcache.hash_strategy | "standard" | INI_ALL | Verfügbar seit Memcache 2.2.0.
memcache.hash_function | "crc32" | INI_ALL | Verfügbar seit Memcache 2.2.0.
memcache.protocol | ascii | INI_ALL | Unterstützt seit Memcache 3.0.0
memcache.redundancy | 1 | INI_ALL | Unterstützt seit Memcache 3.0.0
memcache.session_redundancy | 2 | INI_ALL | Unterstützt seit Memcache 3.0.0
memcache.compress_threshold | 20000 | INI_ALL | Unterstützt seit Memcache 3.0.3
memcache.lock_timeout | 15 | INI_ALL | Wird seit Memcache 3.0.4 unterstützt
memory_limit | "128M" | INI_ALL |
mysql.allow_local_infile | "1" | INI_SYSTEM |
mysql.allow_persistent | "1" | INI_SYSTEM |
mysql.max_persistent | "-1" | INI_SYSTEM |
mysql.max_links | "-1" | INI_SYSTEM |
mysql.trace_mode | "0" | INI_ALL |
mysql.default_port | NULL | INI_ALL |
mysql.default_socket | NULL | INI_ALL |
mysql.default_host | NULL | INI_ALL |
mysql.default_user | NULL | INI_ALL |
mysql.default_password | NULL | INI_ALL |
mysql.connect_timeout | "60" | INI_ALL |
mysqli.allow_local_infile | "0" | INI_SYSTEM | Vor PHP 7.2.16 und 7.3.3 war der Standardwert "1".
mysqli.local_infile_directory |  | INI_SYSTEM | Verfügbar seit PHP 8.1.0.
mysqli.allow_persistent | "1" | INI_SYSTEM |
mysqli.max_persistent | "-1" | INI_SYSTEM |
mysqli.max_links | "-1" | INI_SYSTEM |
mysqli.default_port | "3306" | INI_ALL |
mysqli.default_socket | NULL | INI_ALL |
mysqli.default_host | NULL | INI_ALL |
mysqli.default_user | NULL | INI_ALL |
mysqli.default_pw | NULL | INI_ALL |
mysqli.reconnect | "0" | INI_SYSTEM | Entfernt in PHP 8.2.0
mysqli.rollback_on_cached_plink | "0" | INI_SYSTEM |
mysqlnd.collect_statistics | "1" | INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | INI_SYSTEM |
mysqlnd.debug | "" | INI_SYSTEM |
mysqlnd.log_mask | 0 | INI_ALL |
mysqlnd.mempool_default_size | 16000 | INI_ALL |
mysqlnd.net_read_timeout | "86400" | INI_ALL | Vor PHP 7.2.0 war der Standardwert "31536000" und die Veränderbarkeit war INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | INI_PERDIR |
mysqlnd.trace_alloc | "" | INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | INI_ALL | Entfernt seit PHP 8.1.0
oci8.connection_class | "" | INI_ALL |
oci8.default_prefetch | "100" | INI_SYSTEM |
oci8.events | Off | INI_SYSTEM |
oci8.max_persistent | "-1" | INI_SYSTEM |
oci8.old_oci_close_semantics | Off | INI_SYSTEM | Ab PHP 8.1.0 veraltet.
oci8.persistent_timeout | "-1" | INI_SYSTEM |
oci8.ping_interval | "60" | INI_SYSTEM |
oci8.prefetch_lob_size | "0" | INI_SYSTEM | Verfügbar seit PECL OCI8 3.2.
oci8.privileged_connect | Off | INI_SYSTEM |
oci8.statement_cache_size | "20" | INI_SYSTEM |
odbc.default_db * | NULL | INI_ALL |
odbc.default_user * | NULL | INI_ALL |
odbc.default_pw * | NULL | INI_ALL |
odbc.allow_persistent | "1" | INI_SYSTEM |
odbc.check_persistent | "1" | INI_SYSTEM |
odbc.max_persistent | "-1" | INI_SYSTEM |
odbc.max_links | "-1" | INI_SYSTEM |
odbc.defaultlrl | "4096" | INI_ALL |
odbc.defaultbinmode | "1" | INI_ALL |
odbc.default_cursortype | "3" | INI_ALL |
opcache.enable | "1" | INI_ALL |
opcache.enable_cli | "0" | INI_SYSTEM | Between PHP 7.1.2 and 7.1.6 inclusive, the default was "1"
opcache.memory_consumption | "128" | INI_SYSTEM |
opcache.interned_strings_buffer | "8" | INI_SYSTEM |
opcache.max_accelerated_files | "10000" | INI_SYSTEM |
opcache.max_wasted_percentage | "5" | INI_SYSTEM |
opcache.use_cwd | "1" | INI_SYSTEM |
opcache.validate_timestamps | "1" | INI_ALL |
opcache.revalidate_freq | "2" | INI_ALL |
opcache.revalidate_path | "0" | INI_ALL |
opcache.save_comments | "1" | INI_SYSTEM |
opcache.fast_shutdown | "0" | INI_SYSTEM | Removed in PHP 7.2.0
opcache.enable_file_override | "0" | INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | INI_SYSTEM | Changed from 0x7FFFBFFF in PHP 7.3.0
opcache.inherited_hack | "1" | INI_SYSTEM | Removed in PHP 7.3.0
opcache.dups_fix | "0" | INI_ALL |
opcache.blacklist_filename | "" | INI_SYSTEM |
opcache.max_file_size | "0" | INI_SYSTEM |
opcache.consistency_checks | "0" | INI_ALL | Disabled as of 8.1.18 and 8.2.5. Removed as of PHP 8.3.0.
opcache.force_restart_timeout | "180" | INI_SYSTEM |
opcache.error_log | "" | INI_SYSTEM |
opcache.log_verbosity_level | "1" | INI_SYSTEM |
opcache.record_warnings | "0" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.preferred_memory_model | "" | INI_SYSTEM |
opcache.protect_memory | "0" | INI_SYSTEM |
opcache.mmap_base | null | INI_SYSTEM |
opcache.restrict_api | "" | INI_SYSTEM |
opcache.file_update_protection | "2" | INI_ALL |
opcache.huge_code_pages | "0" | INI_SYSTEM |
opcache.lockfile_path | "/tmp" | INI_SYSTEM |
opcache.opt_debug_level | "0" | INI_SYSTEM | Available as of PHP 7.1.0
opcache.file_cache | NULL | INI_SYSTEM |
opcache.file_cache_only | "0" | INI_SYSTEM |
opcache.file_cache_consistency_checks | "1" | INI_SYSTEM |
opcache.file_cache_fallback | "1" | INI_SYSTEM | Windows only.
opcache.validate_permission | "0" | INI_SYSTEM | Available as of PHP 7.0.14
opcache.validate_root | "0" | INI_SYSTEM | Available as of PHP 7.0.14
opcache.preload | "" | INI_SYSTEM | Available as of PHP 7.4.0
opcache.preload_user | "" | INI_SYSTEM | Available as of PHP 7.4.0
opcache.cache_id | "" | INI_SYSTEM | Windows only. Available as of PHP 7.4.0
opcache.jit | "tracing" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_buffer_size | "0" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_debug | "0" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_bisect_limit | "0" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_prof_threshold | "0.005" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_root_traces | "1024" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_max_side_traces | "128" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_max_exit_counters | "8192" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_loop | "64" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_func | "127" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_return | "8" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_side_exit | "8" | INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_blacklist_root_trace | "16" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_blacklist_side_trace | "8" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_loop_unrolls | "8" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_recursive_calls | "2" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_recursive_returns | "2" | INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_polymorphic_calls | "2" | INI_ALL | Available as of PHP 8.0.0
open_basedir | null | INI_ALL |
output_buffering | "0" | INI_PERDIR |
output_handler | null | INI_PERDIR |
pcre.backtrack_limit | "1000000" | INI_ALL |
pcre.recursion_limit | "100000" | INI_ALL |
pcre.jit | "1" | INI_ALL |
pdo.dsn.* |  | Nur php.ini |
pdo_odbc.connection_pooling | "strict" | INI_ALL |
pdo_odbc.db2_instance_name | NULL | INI_SYSTEM | Dieses veraltete Feature wird in der Zukunft sicherlich entfernt.
pgsql.allow_persistent | "1" | INI_SYSTEM |
pgsql.max_persistent | "-1" | INI_SYSTEM |
pgsql.max_links | "-1" | INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | INI_SYSTEM |
pgsql.ignore_notice | "0" | INI_ALL |
pgsql.log_notice | "0" | INI_ALL |
phar.readonly | "1" | INI_ALL |
phar.require_hash | "1" | INI_ALL |
phar.cache_list | "" | INI_SYSTEM |
post_max_size | "8M" | INI_PERDIR |
precision | "14" | INI_ALL |
realpath_cache_size | "16K" | INI_SYSTEM |
realpath_cache_ttl | "120" | INI_SYSTEM |
register_argc_argv | "1" | INI_PERDIR |
report_memleaks | "1" | INI_ALL |
report_zend_debug | "1" | INI_ALL |
request_order | "" | INI_PERDIR |
runkit.superglobal | "" | INI_PERDIR |
runkit.internal_override | "0" | INI_SYSTEM |
sendmail_from | null | INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | INI_SYSTEM |
serialize_precision | "-1" | INI_ALL | Vor PHP 7.1.0 war der Standardwert 17.
session.save_path | "" | INI_ALL |
session.name | "PHPSESSID" | INI_ALL |
session.save_handler | "files" | INI_ALL |
session.auto_start | "0" | INI_PERDIR |
session.gc_probability | "1" | INI_ALL |
session.gc_divisor | "100" | INI_ALL |
session.gc_maxlifetime | "1440" | INI_ALL |
session.serialize_handler | "php" | INI_ALL |
session.cookie_lifetime | "0" | INI_ALL |
session.cookie_path | "/" | INI_ALL |
session.cookie_domain | "" | INI_ALL |
session.cookie_secure | "0" | INI_ALL | Vor PHP 7.2.0 war die Grundeinstellung "".
session.cookie_httponly | "0" | INI_ALL | Vor PHP 7.2.0 war die Grundeinstellung "".
session.cookie_samesite | "" | INI_ALL | Verfügbar seit PHP 7.3.0.
session.use_strict_mode | "0" | INI_ALL |
session.use_cookies | "1" | INI_ALL |
session.use_only_cookies | "1" | INI_ALL |
session.referer_check | "" | INI_ALL |
session.cache_limiter | "nocache" | INI_ALL |
session.cache_expire | "180" | INI_ALL |
session.use_trans_sid | "0" | INI_ALL |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | INI_ALL | Verfügbar seit PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | INI_ALL | Verfügbar seit PHP 7.1.0.
session.sid_length | "32" | INI_ALL | Verfügbar seit PHP 7.1.0.
session.sid_bits_per_character | "4" | INI_ALL | Verfügbar seit PHP 7.1.0.
session.upload_progress.enabled | "1" | INI_PERDIR |
session.upload_progress.cleanup | "1" | INI_PERDIR |
session.upload_progress.prefix | "upload_progress_" | INI_PERDIR |
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | INI_PERDIR |
session.upload_progress.freq | "1%" | INI_PERDIR |
session.upload_progress.min_freq | "1" | INI_PERDIR |
session.lazy_write | "1" | INI_ALL |
session.hash_function | "0" | INI_ALL | Entfernt in PHP 7.1.0
session.hash_bits_per_character | "4" | INI_ALL | Entfernt in PHP 7.1.0
session.entropy_file | "" | INI_ALL | Entfernt in PHP 7.1.0
session.entropy_length | "0" | INI_ALL | Entfernt in PHP 7.1.0
short_open_tag | "1" | INI_PERDIR |
SMTP | "localhost" | INI_ALL |
smtp_port | "25" | INI_ALL |
soap.wsdl_cache_enabled | 1 | INI_ALL |
soap.wsdl_cache_dir | /tmp | INI_ALL |
soap.wsdl_cache_ttl | 86400 | INI_ALL |
soap.wsdl_cache | 1 | INI_ALL |
soap.wsdl_cache_limit | 5 | INI_ALL |
sql.safe_mode | "0" | INI_SYSTEM | Seit PHP 7.2.0 entfernt
sqlite3.extension_dir | "" | INI_SYSTEM |
sqlite3.defensive | 1 | INI_USER | Verfügbar von PHP 7.2.17 und 7.3.4 an für libsqlite = 3.26.0. Vor PHP 8.2.0 war diese Einstellung nur über INI_SYSTEM änderbar.
syslog.facility | "LOG_USER" | INI_SYSTEM | Verfügbar von PHP 7.3.0 an.
syslog.filter | "no-ctrl" | INI_ALL | Verfügbar von PHP 7.3.0 an.
syslog.ident | "php" | INI_SYSTEM | Verfügbar von PHP 7.3.0 an.
sys_temp_dir | "" | INI_SYSTEM |
sysvshm.init_mem | 10000 | INI_SYSTEM |
tidy.default_config | "" | INI_SYSTEM |
tidy.clean_output | "0" | INI_USER |
track_errors | "0" | INI_ALL | Von PHP 7.2.0 an missbilligt, ab PHP 8.0.0 entfernt.
unserialize_callback_func | null | INI_ALL |
unserialize_max_depth | "4096" | INI_ALL | Verfügbar seit PHP 7.4.0.
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | INI_ALL |
upload_max_filesize | "2M" | INI_PERDIR |
max_file_uploads | 20 | INI_SYSTEM |
upload_tmp_dir | null | INI_SYSTEM |
url_rewriter.hosts | "" | INI_ALL | Verfügbar seit PHP 7.1.0.
url_rewriter.tags | "form=" | INI_ALL | Vor PHP 7.1.0 war der Standardwert "a=href,area=href,frame=src,form=,fieldset=".
user_agent | null | INI_ALL |
user_dir | null | INI_SYSTEM |
user_ini.cache_ttl | "300" | INI_SYSTEM |
user_ini.filename | ".user.ini" | INI_SYSTEM |
uopz.disable | "0" | INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
variables_order | "EGPCS" | INI_PERDIR |
windows.show_crt_warning | "0" | INI_ALL |
xbithack | "0" | INI_ALL |
xmlrpc_errors | "0" | INI_SYSTEM |
xmlrpc_error_number | "0" | INI_ALL |
yaz.keepalive | "120" | INI_ALL |
yaz.log_mask | null | INI_ALL | Verfügbar seit yaz 1.0.3.
zend.assertions | "1" | INI_ALL |
zend.detect_unicode | "1" | INI_ALL |
zend.enable_gc | "1" | INI_ALL |
zend.multibyte | "0" | INI_PERDIR |
zend.script_encoding | null | INI_ALL |
zend.signal_check | "0" | INI_SYSTEM |
zend_extension | null | Nur php.ini |
zlib.output_compression | "0" | INI_ALL |
zlib.output_compression_level | "-1" | INI_ALL |
zlib.output_handler | "" | INI_ALL |

User Contributed Notes

There are no user contributed notes for this page.


Liste der php.ini-Abschnitte

Diese Liste beinhaltet die php.ini Abschnitte die Sie für die Konfiguration auf Basis des Host- oder Pfadnames nutzen können. Diese Abschnitte sind optional.

Die Abschnitte selbst beeinflussen PHP nicht direkt. Sie werden genutzt um andere php.ini Direktiven zu gruppieren und sie für einen bestimmten Host- oder Pfadnamen anzuwenden.

Diese Abschnitte werden nur benutzt, wenn PHP über CGI/FastCGI operiert, und können extension und zend_extension nicht setzen.

Abschnitte
Name | Veränderbar | Changelog
[HOST=] | INI_SYSTEM |
[PATH=] | INI_SYSTEM |

Hier eine kurze Erklärung der Konfigurationsoptionen:

[HOST=<host>]

Dieser Abschnitt gestattet die Definition einer Gruppe von php.ini Direktiven die für einen bestimmten Host Anwendung finden sollen.

Beispiel #1 Aktiviere volle Fehlerausgaben im Browser für die dev. Domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Dieser Abschnitt gestattet die Definition einer Gruppe von php.ini Direktiven die für einen bestimmten Pfad Anwendung finden sollen.

Beispiel #2 Binde für ein zu sicherndes Verzeichnis ein Sicherheitsscript hinzu

[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).


Beschreibung der php.ini-Direktiven des Sprachkerns

Diese Liste enthält die php.ini-Direktiven des PHP-Kerns, die Sie in Ihrer Installation verwenden können. Direktiven, die von einer der Erweiterungen verarbeitet werden, werden in den Handbuchseiten der jeweiligen Erweiterung aufgelistet und im Detail beschrieben. So können z. B. die Direktiven zur Konfiguration von Sessions auf den Session-Handbuchseiten gefunden werden.

Hinweis:

Die Voreinstellungen, die hier aufgeführt werden, gelten, wenn php.ini nicht geladen wurde. Die Werte für die Produktions- und Entwicklungs-php.ini können unterschiedlich sein.

Sprachoptionen

Konfiguration der Sprache und verschiedene weitere Optionen
Name | Standard | Veränderbar | Changelog
short_open_tag | "1" | INI_PERDIR |
precision | "14" | INI_ALL |
serialize_precision | "-1" | INI_ALL | Vor PHP 7.1.0 war der Vorgabewert 17.
disable_functions | "" | Nur INI_SYSTEM |
disable_classes | "" | Nur php.ini |
exit_on_timeout | "" | INI_ALL |
expose_php | "1" | Nur php.ini |
hard_timeout | "2" | INI_SYSTEM | Verfügbar seit PHP 7.1.0.
zend.exception_ignore_args | "0" | INI_ALL | Verfügbar seit PHP 7.4.0
zend.multibyte | "0" | INI_ALL |
zend.script_encoding | NULL | INI_ALL |
zend.detect_unicode | NULL | INI_ALL |
zend.signal_check | "0" | INI_SYSTEM |
zend.assertions | "1" | INI_ALL mit Einschränkungen |
zend.exception_string_param_max_len | "15" | INI_ALL | Verfügbar seit PHP 8.0.0.

Hier eine kurze Erklärung der Konfigurationsoptionen:

short_open_tag bool

Bestimmt, ob die Kurzform (<? ?>) des PHP-Öffnungs-Tags erlaubt werden soll. Wenn Sie PHP in Kombination mit XML verwenden wollen, können Sie diese Option deaktivieren, um <?xml ?> verwenden zu können. Andernfalls können Sie das Tag mit PHP ausgeben, z. B. <?php echo '<?xml version="1.0"'; ?>. Wenn diese Option deaktiviert ist, müssen Sie die Langform des PHP-Öffnungs-Tags (<?php ?>) verwenden.

Hinweis:

Diese Option hat keinen Einfluss auf die Kurzform <?=, die immer verfügbar ist.

precision int
Die Anzahl der signifikanten Stellen, die in Gleitkommazahlen dargestellt werden. -1 bedeutet, dass ein verbesserter Algorithmus zur Rundung solcher Zahlen verwendet wird.
serialize_precision int
Die Anzahl der signifikanten Stellen, die gespeichert werden, wenn Gleitkommazahlen serialisiert werden. -1 bedeutet, dass ein verbesserter Algorithmus zur Rundung solcher Zahlen verwendet wird.
expose_php bool

Zeigt der Welt, dass PHP auf dem Server installiert ist. Dies beinhaltet die Version von PHP im HTTP-Header (z. B. X-Powered-By: PHP/5.3.7).

disable_functions string

Diese Direktive ermöglicht das Deaktivieren einzelner Funktionen. Die Funktionen werden als kommagetrennte Liste von Funktionsnamen übergeben.

Nur interne Funktionen können über diese Option deaktiviert werden. Benutzerdefinierte Funktionen sind nicht betroffen.

Diese Direktive muss in der php.ini gesetzt werden. Sie kann beispielsweise nicht in der httpd.conf gesetzt werden.

disable_classes string
Diese Direktive ermöglicht das Deaktivieren einzelner Klassen. Die Klassen werden als kommagetrennte Liste von Klassennamen übergeben. Diese Direktive muss der in php.ini gesetzt werden. Sie kann beispielsweise nicht der in httpd.conf gesetzt werden.
zend.assertions int
Falls diese Direktive auf 1 gesetzt ist, dann wird Assertion-Code erzeugt und ausgeführt (Entwicklungsmodus). Falls sie auf 0 gesetzt ist, dann wird Assertion-Code erzeugt, aber zur Laufzeit ausgelassen (nicht ausgeführt). Falls sie auf -1 gesetzt ist, dann wird Assertion-Code nicht erzeugt, so dass die Assertions keine Laufzeitkosten haben (Produktionsmodus).

Hinweis:

Wurde der Prozess im Produktionsmodus gestartet, kann zend.assertions nicht zur Laufzeit geändert werden, da der Assertion-Code nicht erzeugt wurde.

Wurde der Prozess im Entwicklungsmodus gestartet, kann zend.assertions zur Laufzeit nicht auf -1 gesetzt werden.

zend.exception_string_param_max_len int
Die maximale Länge von String-Funktionsparametern in stringifizierten Stacktraces; muss zwischen "0" und "1000000" liegen.
hard_timeout int

Wenn der in max_execution_time eingestellte Timeout erreicht wurde, baut die PHP-Laufzeitumgebung die Ressourcen geordnet ab. Wird dabei etwas blockiert, läuft der harte Timeout für die eingestellte Anzahl von Sekunden. Wenn der harte Timeout erreicht ist, wird PHP unvorschriftsmäßig beendet. Bei einem Wert von 0 wird der harte Timeout nie aktiviert.

Wenn PHP nach einem harten Timeout beendet wird, sieht das in etwa so aus:

Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0

zend.exception_ignore_args bool

Schließt Argumente aus Stacktraces, die von Exceptions generiert wurden, aus.

zend.multibyte bool

Erlaubt das Parsen von Quellcode-Dateien in Multibyte-Kodierungen. Die Aktivierung von zend.multibyte ist erforderlich, um Zeichenkodierungen wie SJIS, BIG5, usw. zu verwenden, die besondere Zeichen in multibyte-Zeichenkettendaten enthalten. ISO-8859-1-kompatible Kodierungen wie UTF-8, EUC usw. erfordern diese Option nicht.

Das Aktivieren von zend.multibyte erfordert, dass die mbstring-Erweiterung verfügbar ist.

zend.script_encoding string

Dieser Wert wird verwendet, sofern am Anfang des Skripts keine declare(encoding=...)-Direktive verwendet wird. Wird eine ISO-8859-1-inkompatible Kodierung verwendet, müssen sowohl zend.multibyte als auch zend.script_encoding verwendet werden.

Zeichenkettenliterale werden von zend.script_encoding in mbstring.internal_encoding übersetzt, als ob mb_convert_encoding() aufgerufen worden wäre.

zend.detect_unicode bool

Erkenne, ob eine BOM (Byte Order Mark) vorhanden ist und prüfe, ob die Datei valide Multibyte-Zeichen enthält. Diese Erkennung wird vorgenommen, bevor __halt_compiler() verarbeitet wird. Diese Option ist nur im Zend-Multibyte-Modus verfügbar.

zend.signal_check bool

Legt fest, ob während des Herunterfahrens geprüft werden soll, ob Signal-Handler ersetzt wurden.

exit_on_timeout bool

Diese Einstellung betrifft nur Apache1 mit mod_php. Sie zwingt einen Apache-Kindprozess, sich zu beenden, wenn ein PHP-Timeout auftritt. Solch ein Timeout verursacht einen internen longjmp()-Aufruf, welches einige Erweiterungen in einem inkonsistenten Zustand hinterlassen kann. Durch das Beenden des Prozesses werden ausstehende Locks und allozierter Arbeitsspeicher freigegeben.

Limitierung von Ressourcen

Limitierung von Ressourcen
Name | Standard | Veränderbar | Changelog
memory_limit | "128M" | INI_ALL |

Hier eine kurze Erklärung der Konfigurationsoptionen:

memory_limit int

Legt die maximale Menge an Speicher in Bytes fest, die ein Skript verbrauchen darf. Damit können schlecht geschriebene Skripte daran gehindert werden, den gesamten verfügbaren Speicher eines Servers "aufzufressen". Um keine Speicherobergrenze festzulegen, setzen Sie diese Direktive auf den Wert -1.

Wird ein Wert vom Typ int verwendet, wird dieser Wert in Bytes gemessen. Es kann auch die Kurzschreibweise verwendet werden, wie in dieser FAQ beschrieben.

Siehe auch max_execution_time.

Leistungsoptimierung

Leistungsoptimierung
Name | Standard | Veränderbar | Changelog
realpath_cache_size | "4M" | INI_SYSTEM | Vor PHP 7.0.16 and 7.1.2 war die Voreinstellung "16K"
realpath_cache_ttl | "120" | INI_SYSTEM |

Hinweis:

Die Verwendung von open_basedir deaktiviert den realpath-Cache.

Hier eine kurze Erklärung der Konfigurationsoptionen:

realpath_cache_size int

Legt die Größe des von PHP nutzbaren realpath-Caches fest. Dieser Wert sollte auf Systemen erhöht werden, auf denen PHP viele Dateien öffnet, um die Anzahl von Dateioperationen widerzuspiegeln.

Die Größe stellt die Gesamtzahl von Bytes der gespeicherten Pfad-Zeichenketten dar, plus die Größe der Daten, die mit dem Cache-Eintrag verknüpft sind. Das bedeutet, dass der Cache größer sein muss, um längere Pfade im Cache zu speichern. Dieser Wert steuert nicht direkt die Anzahl der individuellen Pfade, die im Cache vorgehalten werden können.

Die benötigte Größe für die Cache-Eintragsdaten ist systemabhängig.

realpath_cache_ttl int

Zeitspanne (in Sekunden), während der realpath-Informationen einer Datei oder eines Verzeichnisses gecacht bleiben. Für Systeme, auf denen sich die Dateien kaum ändern, sollte man die Erhöhung dieses Wertes in Betracht ziehen.

Verarbeitung von Daten

Konfigurationsoptionen für die Verarbeitung von Daten
Name | Standard | Veränderbar | Changelog
arg_separator.output | "&" | INI_ALL |
arg_separator.input | "&" | INI_PERDIR |
variables_order | "EGPCS" | INI_PERDIR |
request_order | "" | INI_PERDIR |
auto_globals_jit | "1" | INI_PERDIR |
register_argc_argv | "1" | INI_PERDIR |
enable_post_data_reading | "1" | INI_PERDIR |
post_max_size | "8M" | INI_PERDIR |
auto_prepend_file | NULL | INI_PERDIR |
auto_append_file | NULL | INI_PERDIR |
default_mimetype | "text/html" | INI_ALL |
default_charset | "UTF-8" | INI_ALL |
input_encoding | "" | INI_ALL |
output_encoding | "" | INI_ALL |
internal_encoding | "" | INI_ALL |

Hier eine kurze Erklärung der Konfigurationsoptionen:

arg_separator.output string

Das Trennzeichen, das in von PHP generierten URLs verwendet wird, um Argumente abzutrennen.

arg_separator.input string

Liste der Trennzeichen, die von PHP beim Parsen von URLs zu Variablen verwendet werden.

Hinweis:

Jeder Buchstabe in dieser Option wird als Trennzeichen interpretiert!

variables_order string

Legt die Reihenfolge der EGPCS- (Environment (Umgebungsvariablen), Get, Post, Cookie und Server) Variablenverarbeitung fest. Wenn zum Beispiel variables_order auf "SP" eingestellt ist, wird PHP die superglobals $_SERVER und $_POST, nicht aber $_ENV, $_GET und $_COOKIE anlegen. Wird dieser Wert auf "" gesetzt, so werden keine superglobals erzeugt.

Warnung

Sowohl im CGI- als auch im FastCGI-SAPI enthält $_SERVER immer auch Variablen aus dem Environment; S ist hier immer äquivalent zu ES, unabhängig davon, ob E noch anderweitig in der Direktive verwendet wird.

Hinweis:

Der Inhalt und die Reihenfolge von $_REQUEST sind von dieser Direktive ebenfalls betroffen.

request_order string

Diese Direktive legt fest, in welcher Reihenfolge PHP GET-, POST- und Cookie-Variablen im _REQUEST-Array ablegt. Die Registrierung erfolgt dabei von links nach rechts und neuere Einträge überschreiben bisherige Werte gleichen Namens.

Ist diese Direktive nicht gesetzt, so wird stattdessen variables_order für die Inhalte von $_REQUEST ausgewertet.

Beachten Sie, dass die Standard-php.ini-Dateien 'C' für Cookies aus Sicherheitsgründen nicht angeben.

auto_globals_jit bool

Wenn eingeschaltet, werden die SERVER-, REQUEST- und ENV-Variablen erzeugt, sobald diese zum ersten Mal verwendet werden (Just In Time), statt zum Ausführungsbeginn des Skriptes. Wenn diese Variablen in einem Skript nicht verwendet werden, bringt das Einschalten dieser Einstellung einen Geschwindigkeitszuwachs.

Warnung

Ob SERVER-, REQUEST- und ENV-Variablen verwendet werden, wird bereits zur Kompilationszeit geprüft. Ein Zugriff über variable Variablen führt daher nicht dazu, dass diese initialisiert werden.

register_argc_argv bool
Bestimmt, ob die argv- & argc-Variablen deklariert werden sollen (betrifft die GET-Informationen). Siehe auch Kommandozeile.
enable_post_data_reading bool
Wenn diese Option deaktiviert ist, werden $_POST und $_FILES nicht gefüllt. Der einzige Weg, in diesem Fall die POST-Daten zu lesen, ist der php://input-Stream-Wrapper. Dies kann nützlich sein, um Requests umzuleiten oder um die POST-Daten speichereffizient zu verarbeiten.
post_max_size int
Setzt die maximal erlaubte Größe von POST-Daten. Diese Option betrifft auch den Datei-Upload. Um größere Dateien hochzuladen, muss der Wert größer sein als upload_max_filesize. Allgemein sollte memory_limit größer als post_max_size sein. Wird ein Wert vom Typ int verwendet, wird dieser Wert in Bytes gemessen. Es kann auch die Kurzschreibweise verwendet werden, wie in dieser FAQ beschrieben. Wenn die Größe der POST-Daten größer ist als post_max_size, werden die $_POST- und $_FILES-Superglobals leer sein. Dies kann auf verschiedene Weisen verfolgt werden, z. B. indem man die $_GET-Variable an das Skript, das die Daten verarbeitet, weitergibt, d. h. <form action="edit.php?processed=1"> und daraufhin prüft, ob $_GET['processed'] gesetzt ist.

Hinweis:

PHP gestattet die Angabe von K für kilo, M für mega und G für Giga bei der Angabe von Werten und rechnet diese automatisch um. Vermeiden Sie aber beim Einsatz von 32bit-Versionen die Angabe von Werten, die das Limit für vorzeichenbehaftete 32bit-Integer überschreiten, da Ihre Skripte sonst fehlschlagen werden.

Changelog für post_max_size
Version | Beschreibung
5.3.4 | post_max_size = 0 deaktiviert die Begrenzung nicht, wenn der Content-Type application/x-www-form-urlencoded oder PHP nicht bekannt ist.
5.3.2, 5.2.12 | Erlaubt unbegrenzte POST-Größe durch Setzen von post_max_size auf 0.

auto_prepend_file string

Hier können Sie eine Datei angeben, die automatisch vor der Hauptdatei aufgerufen wird. Die Datei wird in die aufgerufene Datei eingebettet, als wenn Sie sie mittels der Funktion require eingebunden hätten, dabei wird ein gesetzter include_path beachtet.

Der spezielle Wert none deaktiviert Auto-Prepending.

auto_append_file string

Hier können Sie eine Datei angeben, die automatisch nach der Hauptdatei aufgerufen wird. Die Datei wird in die aufgerufene Datei eingebettet, als wenn Sie sie mittels der Funktion require eingebunden hätten, dabei wird ein gesetzter include_path beachtet.

Der spezielle Wert none deaktiviert Auto-Appending.

Hinweis: Wird das Skript mit der Funktion exit() beendet, dann wird Auto-Appending nicht aktiv.

default_mimetype string

Standardmäßig gibt PHP den Medientyp unter Verwendung des Content-Type-Headers aus. Um das zu unterbinden, ist diese Einstellung leer zu lassen.

PHP's eingebauter Medientyp ist text/html.

default_charset string

"UTF-8" ist der Vorgabewert und dieser Wert wird als Standard-Zeichenkodierung für htmlentities(), html_entity_decode() und htmlspecialchars() verwendet, wenn der Parameter encoding ausgelassen wird. Der Wert von default_charset wird ebenfalls verwendet, um den Standard-Zeichensatz für iconv-Funktionen festzulegen, wenn die iconv.input_encoding-, iconv.output_encoding- und iconv.internal_encoding-Konfigurationsoptionen nicht gesetzt sind, und für mbstring-Funktionen, wenn die mbstring.http_input-, mbstring.http_output- und mbstring.internal_encoding-Konfigurationsoptionen nicht gesetzt sind.

Alle Versionen von PHP verwenden diesen Wert als Zeichensatz im Standard-Content-Type-Header, der von PHP gesendet wird, wenn der Header nicht durch einen Aufruf von header() überschrieben wurde.

default_charset auf einen leeren Wert zu setzen, wird nicht empfohlen.

input_encoding string

Diese Einstellung wird für Multibyte-Module wie mbstring und iconv verwenden. Standardwert ist leer.

output_encoding string

Diese Einstellung wird für Multibyte-Module wie mbstring und iconv verwenden. Standardwert ist leer.

internal_encoding string

Diese Einstellung wird für Multibyte-Module wie mbstring und iconv verwenden. Standardwert ist leer. Falls leer, dann wird default_charset verwendet.

Pfade und Verzeichnisse

Konfigurationsoptionen für Pfade und Verzeichnisse
Name | Standard | Veränderbar | Changelog
include_path | ".;/path/to/php/pear" | INI_ALL |
open_basedir | NULL | INI_ALL |
doc_root | NULL | INI_SYSTEM |
user_dir | NULL | INI_SYSTEM |
user_ini.cache_ttl | "300" | INI_SYSTEM |
user_ini.filename | ".user.ini" | INI_SYSTEM |
extension_dir | "/path/to/php" | INI_SYSTEM |
extension | NULL | Nur php.ini |
zend_extension | NULL | Nur php.ini |
cgi.check_shebang_line | "1" | INI_SYSTEM |
cgi.discard_path | "0" | INI_SYSTEM |
cgi.fix_pathinfo | "1" | INI_SYSTEM |
cgi.force_redirect | "1" | INI_SYSTEM |
cgi.nph | "0" | INI_SYSTEM |
cgi.redirect_status_env | NULL | INI_SYSTEM |
cgi.rfc2616_headers | "0" | INI_ALL |
fastcgi.impersonate | "0" | INI_SYSTEM |
fastcgi.logging | "1" | INI_SYSTEM |

Hier eine kurze Erklärung der Konfigurationsoptionen:

include_path string

Hier können Sie eine Liste von Verzeichnissen angeben, in welchen die Funktionen require, include, fopen(), file(), readfile() und file_get_contents() nach Dateien suchen. Das Format ist ähnlich zur PATH-Umgebungsvariablen des jeweiligen Systems: Eine Liste von Verzeichnissen, getrennt durch einen Doppelpunkt unter Unix oder ein Semikolon unter Windows.

Wenn PHP eine Datei einbinden soll, geht es alle Einträge im Include-Pfad einzeln durch. Zuerst wird der erste Pfad getestet und wenn die Datei dort nicht gefunden wird, wird der nächste Pfad überprüft, bis letztendlich entweder die Datei gefunden wird oder aber PHP ein E_WARNING oder E_ERROR zurückgibt. Der Include-Pfad kann auch zur Laufzeit mit Hilfe der Funktion set_include_path() geändert werden.

Beispiel #1 include_path unter Unix

include_path=".:/php/includes"

Beispiel #2 include_path unter Windows

include_path=".;c:\php\includes"

Ein . in dieser Option ermöglicht, Dateien relativ zum aktuellen Verzeichnis einzubinden. Es ist jedoch effizienter, explizit include './Datei' zu schreiben, anstatt PHP zu zwingen jedes Mal den Include-Pfad zu nutzen.

Hinweis:

Auf ENV-Variablen kann in .ini-Dateien ebenfalls zugegriffen werden. Daher ist es möglich, das Home-Verzeichnis durch ${LOGIN} und ${USER} zu referenzieren.

Umgebungsvariablen können zwischen verschiedenen Server-APIs variieren, da diese Umgebungen unterschiedlich sein können.

Beispiel #3 include_path unter Unix unter Verwendung der ${USER}-Umgebungsvariablen

include_path = ".:${USER}/pear/php"

open_basedir string

Begrenzt die Dateien, auf die von PHP zugegriffen werden kann, auf einen bestimmten Ordner inklusive seiner Unterordner.

Wenn ein Skript versucht, auf eine Datei zuzugreifen, zum Beispiel mit include oder fopen(), wird der Ort der Datei geprüft. Wenn die Datei nicht im Verzeichnisbaum liegt, der in open_basedir angegeben ist, wird PHP nicht auf die Datei zugreifen. Alle symbolischen Verknüpfungen werden aufgelöst, sodass es nicht möglich ist, diese Beschränkung mit einem Symlink zu umgehen. Wenn die Datei nicht existiert, kann die Verknüpfung nicht aufgelöst werden und der Dateiname wird mit (einem aufgelösten) open_basedir verglichen.

open_basedir kann sich auf mehr als nur Dateisystemfunktionen auswirken. Wenn zum Beispiel MySQL so konfiguriert ist, dass es den mysqlnd-Treiber verwendet, wird LOAD DATA INFILE von open_basedir beeinflusst. Ein Großteil der erweiterten Funktionalität von PHP verwendet open_basedir auf diese Weise.

Der spezielle Wert . gibt an, dass das Arbeitsverzeichnes des Skriptes als Basis-Verzeichnis verwendet wird. Dies ist gefährtlich, da das Arbeitsverzeichnis mit chdir() einfach geändert werden kann.

In der Konfigurationsdatei httpd.conf kann open_basedir genau wie jede andere Direktive mit "php_admin_value open_basedir none" geändert oder deaktiviert werden (z. B. für einige virtuelle Hosts).

Unter Windows müssen die Verzeichnisse mit einem Semikolon getrennt werden, auf allen anderen Systemen mit einem Doppelpunkt. Wenn PHP als Apache-Modul läuft, erbt open_basedir seinen Pfad nun automatisch von übergeordneten Verzeichnissen.

Die mit open_basedir angegebene Einschränkung ist ein Verzeichnisname, kein Präfix.

Standardmäßig dürfen alle Dateien geöffnet werden.

Hinweis:

open_basedir kann zur Laufzeit weiter eingeschränkt werden. Das heißt, wenn open_basedir laut php.ini auf /www/ gesetzt ist, kann die Direktive zur Laufzeit mit ini_set() beispielsweise weiter auf /www/tmp/ begrenzt werden. Wenn mehrere Verzeichnisse aufgelistet werden, kann die Konstante PATH_SEPARATOR unabhängig vom Betriebssystem als Trennzeichen verwendet werden.

Hinweis:

Die Verwendung von open_basedir setzt realpath_cache_size auf 0 und deaktiviert somit den realpath-Cache.

Achtung

open_basedir ist nur ein zusätzliches Sicherheitsnetz, das in keiner Weise umfassend ist und daher nicht als verlässlich angesehen werden kann, wenn Sicherheit erforderlich ist.

doc_root string

Hier wird das Stammverzeichnis der PHP-Skripte auf dem Server angegeben. Diese Option wird nur verwendet, wenn ein Wert angegeben wird. Wenn PHP nicht mit FORCE_REDIRECT kompiliert wurde, sollten Sie doc_root setzen, wenn Sie PHP als CGI-Version laufen lassen (betrifft alle Webserver außer IIS). Die Alternative ist, die Option cgi.force_redirect zu verwenden.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

Der Basisname des Verzeichnisses, das für Benutzer-Verzeichnisse mit PHP-Dateien verwendet wird, z. B. public_html.

extension_dir string

Das Verzeichnis, in dem PHP dynamisch zu ladende Erweiterungen findet. Es wird empfohlen, einen absoluten Pfad anzugeben. Siehe auch enable_dl und dl().

extension string

Dynamisch zu ladende Erweiterungen, die geladen werden sollen, wenn PHP gestartet wird.

zend_extension string

Der Name einer dynamisch ladbaren Zend-Erweiterung (beispielsweise Xdebug), welche geladen werden soll, wenn PHP startet.

cgi.check_shebang_line bool

Kontrolliert, ob die CGI-Version von PHP am Anfang des auszuführenden Skripts nach einer Zeile sucht, die mit #! (Shebang) beginnt. Diese Zeile könnte notwendig sein, wenn das Skript sowohl die eigenständige Ausführung als auch die mittels PHP-CGI unterstützt. PHP überspringt diese Zeile im CGI-Modus und ignoriert ihren Inhalt, wenn diese Direktive eingeschaltet ist.

cgi.discard_path bool

Ist dies aktiviert, kann das PHP-CGI-Binary sicher außerhalb des Web-Verzeichnisbaums abgelegt werden, ohne dass jemand in der Lage ist, die .htaccess-Sicherheit zu umgehen.

cgi.fix_pathinfo bool

Stellt echte PATH_INFO/PATH_TRANSLATED-Unterstützung für CGI zur Verfügung. Das frühere Verhalten von PHP war, PATH_TRANSLATED einfach auf SCRIPT_FILENAME zu setzen und nicht auf PATH_INFO. Für weitere Informationen zu PATH_INFO siehe die CGI-Spezifikation. Wenn Sie diesen Wert auf 1 setzen, hat dies zur Folge, dass PHP-CGI seine Pfade entsprechend der Spezifikation anpasst. Bei einem Wert von Null verhält sich PHP entsprechend den früheren Versionen. Standardmäßig ist es eingeschaltet. Es wird empfohlen, Ihre Skripte dahingehend anzupassen, statt PATH_TRANSLATED SCRIPT_FILENAME zu verwenden.

cgi.force_redirect bool

Wenn PHP als CGI-Version läuft, wird unter den meisten Webservern cgi.force_redirect benötigt, um Sicherheit zu garantieren. Wenn diese Option nicht angegeben wird, setzt PHP sie standardmäßig auf "on". Auf Ihre eigene Gefahr hin können Sie dies ausschalten ("off").

Hinweis:

Windows-Benutzer: Unter IIS muss diese Option ausgeschaltet werden. Für OmniHTTPD und Xitami gilt selbiges.

cgi.nph bool

Ist cgi.nph aktiviert, zwingt es CGI immer, Status: 200 für jede Anfrage zu senden.

cgi.redirect_status_env string

Wenn cgi.force_redirect eingeschaltet ist und Sie nicht den Apache- oder Netscape-Webserver (iPlanet) verwenden, müssen Sie eventuell eine Umgebungsvariable setzen, damit PHP weiß, ob es die Ausführung fortführen darf.

Hinweis:

Das Setzen dieser Variablen kann Sicherheitsrisiken verursachen, Sie sollten also genau wissen, was Sie tun.

cgi.rfc2616_headers int

Bestimmt, welcher Typ von Headern verwendet werden soll, wenn HTTP-Antwortcodes gesendet werden. Wenn diese Option auf 0 gesetzt ist, sendet PHP einen » RFC 3875-"Status:"-Header, der von Apache und anderen Webservern unterstützt wird. Ist sie auf 1 gesetzt, sendet PHP einen zu » RFC 2616 konformen Header.

Ist diese Option aktiviert, und Sie führen PHP in einer CGI-Umgebung (z. B. PHP-FPM) aus, sollten Sie keine üblichen RFC 2616 HTTP Status-Response-Header verwenden; stattdessen sollten Sie ihre RFC 3875-Pendants nutzen, z. B. sollten Sie anstelle von header("HTTP/1.0 404 Not found"); header("Status: 404 Not Found"); verwenden.

Wenn Sie diese Option nicht verstehen, lassen Sie den Wert auf 0.

fastcgi.impersonate string

FastCGI unterstützt unter dem IIS (auf WINNT-basierten Betriebssystemen) die Möglichkeit, Sicherheitsmerkmale des aufrufenden Clients zu bestimmen. Dies ermöglicht es dem IIS, den Sicherheitskontext zu bestimmen, in dem der Zugriff läuft. mod_fastcgi unter Apache unterstützt diese Funktion zur Zeit nicht (17.03.2002). Setzen Sie diese Option auf 1, wenn Sie den IIS verwenden. Der Standardwert ist 0.

fastcgi.logging bool

Schaltet das SAPI-Logging an, wenn FastCGI verwendet wird. Standardmäßig ist das Logging aktiviert.

Datei-Uploads

Konfigurationsoptionen für Datei-Uploads
Name | Standard | Veränderbar | Changelog
file_uploads | "1" | INI_SYSTEM |
upload_tmp_dir | NULL | INI_SYSTEM |
max_input_nesting_level | 64 | INI_PERDIR |
max_input_vars | 1000 | INI_PERDIR |
upload_max_filesize | "2M" | INI_PERDIR |
max_file_uploads | 20 | INI_PERDIR |

Hier eine kurze Erklärung der Konfigurationsoptionen:

file_uploads bool

Bestimmt, ob Datei-Uploads per HTTP erlaubt sind. Siehe auch die Optionen upload_max_filesize, upload_tmp_dir und post_max_size.

upload_tmp_dir string

Das temporäre Verzeichnis, in dem Dateien während des Uploads gespeichert werden. Für dieses Verzeichnis muss der Benutzer, unter dem PHP läuft, Schreibberechtigung haben. Wenn hier nichts angeben wird, verwendet PHP das Standardverzeichnis des Systems.

Wenn das hier angegebene Verzeichnis nicht beschreibbar ist, nutzt PHP stattdessen das Standardverzeichnis für temporäre Dateien. Wenn open_basedir genutzt wird, muss dieses Standardverzeichnis erlaubt sein, damit Uploads funktionieren.

upload_max_filesize int

Die maximale Größe, die eine hochgeladene Datei haben darf.

post_max_size muss größer als dieser Wert sein.

Wird ein Wert vom Typ int verwendet, wird dieser Wert in Bytes gemessen. Es kann auch die Kurzschreibweise verwendet werden, wie in dieser FAQ beschrieben.
max_file_uploads int

Die maximale Anzahl an Dateien, die gleichzeitig hochgeladen werden kann. Upload-Formularfelder, die leer gelassen wurden, zählen nicht zu diesem Limit.

Allgemeines SQL

Konfigurationsoptionen für allgemeines SQL
Name | Standard | Veränderbar | Changelog
sql.safe_mode | "0" | INI_SYSTEM | Entfernt in PHP 7.2.0

Hier eine kurze Erklärung der Konfigurationsoptionen:

sql.safe_mode bool

Wenn diese Option eingeschaltet wird, werden Datenbankverbindungsfunktionen, die Standardwerte vorgeben, diese Werte anstelle der angegebenen Parameter verwenden. Zu Informationen über die Standardwerte können Sie einen Blick auf die Dokumentation der Verbindungsfunktionen der jeweiligen Datenbank werfen.

Warnung

Dieses Feature wurde von PHP 7.2.0 an ENTFERNT.

Windows-spezifisch

Windows-spezifische Optionen
Name | Standard | Veränderbar | Changelog
windows.show_crt_warning | "0" | INI_ALL |

Hier eine kurze Erklärung der Konfigurationsoptionen:

windows.show_crt_warning bool

Wenn diese Direktive angeschaltet ist, werden Windows CRT Warnings angezeigt.

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


Extension-Liste/-Kategorisierung

Inhaltsverzeichnis

  • Alphabetisch
  • Zugehörigkeit
  • Status

Dieser Anhang kategorisiert über 150 im PHP-Handbuch dokumentierte Extensions nach verschiedenen Kriterien.

User Contributed Notes

There are no user contributed notes for this page.


Alphabetisch

  • Apache
  • APCu
  • Arrays
  • BC Math
  • Bzip2
  • Kalender
  • Klassen/Objekte
  • CommonMark
  • COM
  • Componere
  • Ctype
  • CUBRID
  • cURL
  • Datum/Uhrzeit
  • DBA
  • dBase
  • Direct-IO
  • Verzeichnis-Funktionen
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Fehlerbehandlung
  • Ev
  • Event
  • Programmausführung
  • Exif
  • Expect
  • FANN
  • FDF
  • FFI
  • Fileinfo
  • Dateisystem
  • Filter
  • FastCGI Prozess-Manager
  • FTP
  • Function Handling
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • Igbinary
  • GD
  • ImageMagick
  • IMAP
  • PHP-Optionen/-Informationen
  • 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
  • Ausgabekontrolle
  • 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
  • Reflection
  • Rnp
  • RpmInfo
  • RRD
  • runkit7
  • ScoutAPM
  • Seaslog
  • Semaphore
  • Sessions
  • Shared Memory
  • Simdjson
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Streams
  • Zeichenketten
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Variablenbehandlung
  • var_representation
  • Varnish
  • WDDX
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XLSWriter
  • XML Parser
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yac
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • 0MQ messaging
  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Zugehörigkeit

Kern-Extensions

Dies sind eigentlich keine Extensions. Sie sind Teil des PHP-Kerns und können nicht mittels Kompilierungsoptionen aus dem PHP-Binary weggelassen werden.

  • Arrays

  • Klassen/Objekte

  • Datum/Uhrzeit

  • Verzeichnis-Funktionen

  • Fehlerbehandlung

  • Programmausführung

  • Dateisystem

  • FastCGI Prozess-Manager

  • Function Handling

  • Hash

  • PHP-Optionen/-Informationen

  • JSON

  • Mail

  • Math

  • Misc.

  • Network

  • OPcache

  • Ausgabekontrolle

  • Password Hashing

  • PCRE

  • Random

  • Reflection

  • SPL

  • Streams

  • Zeichenketten

  • URLs

  • Variablenbehandlung

Mitgelieferte Extensions

Diese Extensions werden mit PHP ausgeliefert.

  • Apache

  • BC Math

  • Kalender

  • COM

  • Ctype

  • DBA

  • Exif

  • FFI

  • Fileinfo

  • Filter

  • FTP

  • HRTime

  • iconv

  • GD

  • intl

  • Multibyte String

  • Mhash

  • PCNTL

  • PDO

  • Phar

  • phpdbg

  • POSIX

  • Semaphore

  • Sessions

  • Shared Memory

  • Sockets

  • SQLite3

  • Tokenizer

  • Zlib

Externe Extensions

Diese Extensions werden mit PHP ausgeliefert, aber um sie zu kompilieren, werden externe Bibliotheken benötigt.

  • 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

  • XML Parser

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

PECL-Extensions

Diese Extensions sind im » PECL verfügbar. Sie benötigen möglicherweise externe Bibliotheken. Es existieren noch mehr PECL-Extensions, diese sind jedoch bisher nicht im PHP-Handbuch dokumentiert.

  • APCu

  • CommonMark

  • Componere

  • CUBRID

  • dBase

  • Direct-IO

  • Data Structures

  • Eio

  • Ev

  • Event

  • Expect

  • FANN

  • FDF

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Firebird/InterBase

  • IBM DB2

  • Igbinary

  • ImageMagick

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Mcrypt

  • Memcache

  • Memcached

  • mqseries

  • MySQL (Original)

  • Mysql_xdevapi

  • OAuth

  • OpenAL

  • parallel

  • Parle

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • Recode

  • Rnp

  • RpmInfo

  • RRD

  • runkit7

  • ScoutAPM

  • Seaslog

  • Simdjson

  • Solr

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • SVM

  • SVN

  • Swoole

  • Sync

  • Taint

  • TCP

  • Trader

  • UI

  • uopz

  • V8js

  • var_representation

  • Varnish

  • WDDX

  • win32service

  • WinCache

  • wkhtmltox

  • xattr

  • xdiff

  • Xhprof

  • XLSWriter

  • XMLDiff

  • XML-RPC

  • Yac

  • Yaconf

  • Yaf

  • Yaml

  • Yar

  • YAZ

  • 0MQ messaging

  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Status

Dieser Teil zählt Extensions auf, die nicht für den produktiven Einsatz gedacht sind - sie sind entweder zu "alt" (veraltet, nicht länger zur Verwendung empfohlen) oder zu "neu" (experimentell).

Veraltete Extensions

Diese Extensions sollten nicht mehr verwendet werden, normalerweise gibt es eine empfohlene andere Extension.

Experimentelle Extensions

Das Verhalten dieser Extensions - einschließlich der Namen ihrer Funktionen und alles andere über diese Extensions dokumentierte - kann sich in einer zukünftigen Version von PHP ohne Ankündigung ändern. Die Verwendung dieser Extensions geschieht auf eigenes Risko.

  • ImageMagick

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • Rnp

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


Liste der Funktions-Aliase

Es gibt einige PHP-Funktionen, die unter mehr als einem Namen aufgerufen werden können. Für einige dieser Funktionen wie z.B. is_integer() und is_int() gibt es keinen bevorzugten Namen, so dass beide Varianten gleichberechtigt nebeneinander bestehen. Andererseits wurden viele Funktionen in der Vergangenheit im Rahmen von API-Änderungen oder aus anderen Gründen umbenannt und der alte Name nur zur Aufrechterhaltung der Rückwärtskompatibilität weiter unterstützt. Es ist daher nicht empfehlenswert, die ältere Namensform weiter zu benutzen, da dies auf lange Sicht zu nicht portablem Code führen kann. Die folgende Liste kann dabei helfen, alte Skripte auf einen aktuellen Stand zu bringen.

Aliase
Alias | Hauptfunktion | verwendete Extension
_ | 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.


Liste der reservierten Wörter

Inhaltsverzeichnis

  • Liste der Schlüsselwörter
  • Vordefinierte Klassen
  • Vordefinierte Konstanten
  • Liste weiterer reservierter Wörter

Es folgt eine Auflistung vordefinierter Bezeichner in PHP. Sie sollten die reservierten Wörter aus diesen Listen keinesfalls in Ihren Skripten als Bezeichner benutzen, es sei denn, es wird ausdrücklich erlaubt. Die Listen enthalten Schlüsselworte, vordefinierte Variablen, Konstanten und Klassennamen. Beachten Sie bitte auch, dass diese Listen nicht unbedingt vollständig sind.

User Contributed Notes

There are no user contributed notes for this page.


Liste der Schlüsselwörter

Die folgenden Begriffe haben in PHP eine spezielle Bedeutung. Einige von ihnen sehen aus wie Funktionen, einige wie Konstanten usw., in Wirklichkeit handelt es sich aber um Sprachkonstrukte. Keines der folgenden Wörter kann als Name für eine Konstante, Klasse oder Funktion genutzt werden. Allerdings sind sie als Eigenschafts-, Konstanten- und Methodennamen von Klassen, Interfaces und Traits erlaubt, mit der Ausnahme, dass class nicht als Name für eine Konstante verwendet werden darf.

PHP Schlüsselworte
__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 (seit PHP 7.4) | for | foreach
function | global | goto | if | implements
include | include_once | instanceof | insteadof | interface
isset() | list() | match (seit PHP 8.0) | namespace | new
or | print | private | protected | public
readonly (seit PHP 8.1.0) * | require | require_once | return | static
switch | throw | trait | try | unset()
use | var | while | xor | yield
yield from |  |  |  |

* readonly kann als Funktionsname verwendet werden.

Kompilierzeit-Konstanten
__CLASS__ | __DIR__ | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ | __TRAIT__ |  |  |  |

User Contributed Notes

Chocopie 23-Mar-2024 06:27
From php8, reserved keywords such as `Interface` or `Trait` can be used as part of the namespace.

<?php
namespace App\Entity\Interface;

interface FooInterface
{

}

https://wiki.php.net/rfc/namespaced_names_as_token
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.


Vordefinierte Klassen

Dieser Abschnitt listet vordefinierte Standardklassen auf, welche von PHP selbst definiert werden. Von Erweiterungen definierte Klassen werden in den jeweiligen Abschnitten des Manuals beschrieben.

Standardmäßig definierte Klassen

Diese Klassen sind im Standard-Funktionsumfang einer PHP-Distribution enthalten.

Directory
Die Klasse, die von dir() instanziiert wird.
stdClass
Eine generische leere Klasse, die durch die Umwandlung in ein Objekt oder verschiedene Standardfunktionen erstellt wird.
__PHP_Incomplete_Class
Wird unter Umständen von unserialize() erzeugt.
Exception
ErrorException
php_user_filter
Closure
Die vordefinierte finale Klasse Closure wird benutzt, um anonyme Funktionen darzustellen.
Generator
Die vordefinierte finale Klasse Generator wird benutzt, um Generatoren darzustellen.
ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Spezielle Klassen

Die folgenden Bezeichner können nicht als Klassenname genutzt werden, da sie eine besondere Bedeutung haben.

self
Aktuelle Klasse.
static
Aktuelle Klasse zur Laufzeit.
parent
Elternklasse.

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


Vordefinierte Konstanten

Vordefinierte Core-Konstanten

Diese Konstanten werden vom PHP-Core definiert. Das beinhaltet PHP, die Zend-Engine- und SAPI-Module.

PHP_VERSION (string)
Die aktuelle PHP-Version als Zeichenkette im Format "Hauptversion.Unterversion.Release[Extra]".
PHP_MAJOR_VERSION (int)
Die aktuelle "Hauptversion" von PHP als Ganzzahl (z. B. int(5) bei Version "5.2.7-extra").
PHP_MINOR_VERSION (int)
Die aktuelle "Unterversion" von PHP als Ganzzahl (z. B. int(2) bei Version "5.2.7-extra").
PHP_RELEASE_VERSION (int)
Die aktuelle "Release"-Version von PHP als Ganzzahl (z. B. int(7) bei Version "5.2.7-extra").
PHP_VERSION_ID (int)
Die aktuelle PHP-Version als Ganzzahl. Nützlich beispielsweise für Versionsvergleiche (z. B. int(50207) bei Version "5.2.7-extra").
PHP_EXTRA_VERSION (string)
Die aktuelle "Extra"-Versionsnummer von PHP als Zeichenkette (z. B. '-extra' bei Version "5.2.7-extra"). Wird oft von Distributionsanbietern zur Angabe einer Paketversion verwendet.
ZEND_THREAD_SAFE (bool)
Zeigt an, ob der aktuelle Build von PHP thread-sicher ist.
ZEND_DEBUG_BUILD (bool)
Zeigt an, ob der aktuelle Build von PHP ein Debug-Build ist.
PHP_ZTS (int)
Zeigt an, ob der aktuelle Build von PHP thread-sicher ist.
PHP_DEBUG (int)
Zeigt an, ob der aktuelle Build von PHP ein Debug-Build ist.
PHP_MAXPATHLEN (int)
Die maximale Länge von Dateinamen (inklusive Pfad), die von diesem Build von PHP unterstützt wird.
PHP_OS (string)
Das Betriebssystem, für das PHP kompiliert wurde.
PHP_OS_FAMILY (string)
Die Betriebssystemfamilie, für die PHP kompiliert wurde. Eins von 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' oder 'Unknown' (unbekannt). Verfügbar ab PHP 7.2.0.
PHP_SAPI (string)
Die Server-API dieses Builds von PHP. Siehe auch php_sapi_name().
PHP_EOL (string)
Das korrekte Zeilenendezeichen für diese Plattform.
PHP_INT_MAX (int)
Die größtmögliche Ganzzahl, die von diesem Build von PHP unterstützt wird. Üblicherweise int(2147483647) auf 32-bit-Systemen und int(9223372036854775807) auf 64-bit-Systemen.
PHP_INT_MIN (int)
Die kleinsmögliche Ganzzahl, die von diesem Build von PHP unterstützt wird. Üblicherweise int(-2147483648) auf 32-bit-Systemen und int(-922337206854775808) auf 64-bit-Systemen. Üblicherweise ist PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)
Die Größe einer Ganzzahl in Bytes in diesem Build von PHP.
PHP_FLOAT_DIG (int)
Die Anzahl von Dezimalstellen, die zu float und zurück ohne Genauigkeitsverlust gerundet werden können. Verfügbar ab PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
Die kleinste darstellbare positive Zahl x, sodass x + 1.0 != 1.0. Verfügbar ab PHP 7.2.0.
PHP_FLOAT_MIN (float)
Die kleinste darstellbare positive Gleitkommazahl. Um die kleinste darstellbare negative Gleitkommazahl zu erhalten, ist - PHP_FLOAT_MAX zu verwenden. Verfügbar ab PHP 7.2.0.
PHP_FLOAT_MAX (float)
Die größte darstellbare Gleitkommazahl. Verfügbar ab PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
Das Standardverzeichnis, in dem nach dynamisch ladbaren Erweiterungen gesucht werden soll (sofern es nicht durch extension_dir überschrieben wird). Der Standardwert ist PHP_PREFIX (oder PHP_PREFIX . "\\ext" unter Windows).
PHP_PREFIX (string)
Der Wert von --prefix, der während der Konfiguration angegeben wurde. Unter Windows ist dies der Wert von --with-prefix, der während der Konfiguration angegeben wurde.
PHP_BINDIR (string)
Der Wert von --bindir, der während der Konfiguration angegeben wurde. Unter Windows ist dies der Wert von --with-prefix, der während der Konfiguration angegeben wurde.
PHP_BINARY (string)
Gibt den Pfad der Binärdatei von PHP zur Skriptlaufzeit an.
PHP_MANDIR (string)
Gibt den Ort an, an dem die Manpages installiert wurden.
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)
Die Dateiendung für dynamische Bibliotheken der Build-Plattform, beispielsweise "so" (die meisten Unixe) oder "dll" (Windows").
PHP_FD_SETSIZE (int)
Die Höchstanzahl von Dateideskriptoren für select Systemaufrufe. Verfügbar ab PHP 7.1.0.
E_ERROR (int)
Konstante für Fehlermeldungen
E_WARNING (int)
Konstante für Fehlermeldungen
E_PARSE (int)
Konstante für Fehlermeldungen
E_NOTICE (int)
Konstante für Fehlermeldungen
E_CORE_ERROR (int)
Konstante für Fehlermeldungen
E_CORE_WARNING (int)
Konstante für Fehlermeldungen
E_COMPILE_ERROR (int)
Konstante für Fehlermeldungen
E_COMPILE_WARNING (int)
Konstante für Fehlermeldungen
E_USER_ERROR (int)
Konstante für Fehlermeldungen
E_USER_WARNING (int)
Konstante für Fehlermeldungen
E_USER_NOTICE (int)
Konstante für Fehlermeldungen
E_RECOVERABLE_ERROR (int)
Konstante für Fehlermeldungen.
E_DEPRECATED (int)
Konstante für Fehlermeldungen
E_USER_DEPRECATED (int)
Konstante für Fehlermeldungen
E_ALL (int)
Konstante für Fehlermeldungen
E_STRICT (int)
Konstante für Fehlermeldungen
__COMPILER_HALT_OFFSET__ (int)
true (bool)
Siehe Boolesche Werte.
false (bool)
Siehe Boolesche Werte.
null (null)
Siehe Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
Windows-Ereignis CTRL+C. Verfügbar von PHP 7.4.0 an (nur Windows).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
Windows-Ereignis CTRL+BREAK. Verfügbar von PHP 7.4.0 an (nur Windows).
PHP_CLI_PROCESS_TITLE (bool)
Gibt an, ob es möglich ist, den Prozesstitel zu setzen und abzurufen. Nur unter der CLI-SAPI verfügbar.
STDERR (resource)
Ein bereits geöffneter Stream zur Standardfehlerausgabe (stderr). Nur unter der CLI-SAPI verfügbar.
STDIN (resource)
Ein bereits geöffneter Stream zur Standardeingabe (stdin). Nur unter der CLI-SAPI verfügbar.
STDOUT (resource)
Ein bereits geöffneter Stream zur Standardausgabe (stdout). Nur unter der CLI-SAPI verfügbar.

Siehe auch: Magische Konstanten.

Vordefinierte Standard-Konstanten

Alle Konstanten der Kern-Extensions sind in PHP automatisch definiert.

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

}
?>


Liste weiterer reservierter Wörter

Die folgenden Wörter können nicht verwendet werden, um eine Klasse, ein Interface oder einen Trait zu benennen. Vor PHP 8.0 dürfen sie auch nicht in Namensräumen verwendet werden.

Reservierte Wörter
int | float | bool | string
true | false | null | void (von PHP 7.1 an)
iterable (von PHP 7.1 an) | object (von PHP 7.2 an) | mixed (von PHP 8.0 an) | never (von PHP 8.1 an)

Die folgende Liste von Wörtern wurde weich reserviert. Obgleich sie noch immer als Klassen-, Interface- und Traitname verwendet werden können, ist deren Verwendung unbedingt zu vermeiden, da sie in zukünftigen PHP-Versionen verwendet werden könnten.

Weich reservierte Wörter
enum resource numeric

User Contributed Notes

There are no user contributed notes for this page.


Liste der Ressourcen-Typen

Die folgende Liste enthält Funktionen, die PHP-Ressourcen anlegen, nutzen und wieder entfernen. Die Funktion is_resource() kann benutzt werden, um zu prüfen, ob es sich bei einem Variablenwert um eine Ressource handelt, und mit Hilfe der Funktion get_resource_type() kann der genaue Typ der Ressource ermittelt werden.

Ressource-Typen
Name des Ressourcen-Typs | Erzeugt von | Genutzt von | Entfernt von | Definition
AddressInfo | socket_addrinfo_lookup() | socket_addrinfo_bind(), socket_addrinfo_connect(), socket_addrinfo_explain(), | Nichts | AddressInfo (Sockets-Erweiterung)
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2-komprimierte Datei
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() | Verbindung zur CUBRID-Datenbank
persistent cubrid connection | cubrid_pconnect() cubrid_pconnect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() cubrid_lob2_new() | Persistente Verbindung zur CUBRID-Datenbank
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-Anfrage
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | Keine
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() | Keine
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-Mehrfach-Handle
curl_share | curl_share_init() | curl_share_errno(), curl_share_setopt() | curl_share_close() | Gemeinsam genutztes cURL-Handle
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Verweis auf eine DBA-Datenbank
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | Nichts | Persistenter Verweis auf eine DBA-Datenbank
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() | Verweis auf eine Dbase-Datenbank
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 (vor 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-Wörterbuch (vor 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() | FDF-Datei
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-Verbindung (vor 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() | GD-Image (vor PHP 8.0.0)
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | Nichts | GD-Zeichensatz (vor 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() | Verweis auf einen IMAP- oder POP3-Server (vor 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() | Verweis auf eine Interbase-Datenbank
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | Nichts | Persistenter Verweis auf eine Interbase-Datenbank
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase-Abfrage
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase-Ergebnis
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase-Transaktion
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | LDAP-Verbindung (vor 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-Suchergebnis (vor PHP 8.1.0)
ldap result entry | LDAP-Ergebniseintrag (vor PHP 8.1.0)
mailparse_mail_structure | mailparse_msg_create() mailparse_msg_parse_file() | mailparse_msg_extract_part_file() mailparse_msg_extract_part() mailparse_msg_extract_whole_part_file() mailparse_msg_get_part_data() mailparse_msg_get_part() mailparse_msg_get_structure() mailparse_msg_parse() | mailparse_msg_free()
mysql link | mysql_connect() | mysql_affected_rows(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Verweis auf eine MySQL-Datenbank
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | Nichts | Persistenter Verweis auf eine MySQL-Datenbank
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL-Ergebnis
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() | Verbindung zu einer Oracle-Datenbank
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
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Verweis auf eine ODBC-Datenbank
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | Nichts | Persistenter Verweis auf eine ODBC-Datenbank
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC-Ergebnis
birdstep link | Link zu einer Birdstep-Datenbank (vor PHP 7.3.0)
birdstep result | Birdstep-Ergebnis (vor PHP 7.3.0)
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL-Schlüssel
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Öffentlicher Schlüssel
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 (vor PHP 8.1.0)
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_meta_data(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Verweis auf eine PostgreSQL-Datenbank (vor PHP 8.1.0)
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_meta_data(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | Nichts | Persistenter Verweis auf eine PostgreSQL-Datenbank
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL-Ergebnis (vor 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() | Nichts | Pspell-Wörterbuch (vor PHP 8.1.0)
pspell config | pspell_config_create() | pspell_new_config() | Nichts | Pspell-Konfiguration (vor PHP 8.1.0)
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Handle eines Shared-Memory-Blocks (vor PHP 8.0.0)
Socket | socket_accept(), socket_addrinfo_bind(), socket_addrinfo_connect(), socket_create(), socket_create_listen(), socket_import_stream(), socket_wsaprotocol_info_import() | socket_accept(), socket_bind(), socket_clear_error(), socket_connect(), socket_get_option(), socket_getpeername(), socket_getsockname(), socket_last_error(), socket_listen(), socket_read(), socket_recv(), socket_recvfrom(), socket_recvmsg(), socket_select(), socket_send(), socket_sendmsg(), socket_sendto(), socket_set_block(), socket_set_nonblock(), socket_set_option(), socket_shutdown(), socket_write(), socket_wsaprotocol_info_export(), socket_wsaprotocol_info_release() | socket_close() | Socket (Sockets-Erweiterung)
stream | opendir() | readdir(), rewinddir() | closedir() | Verzeichnis-Handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | Datei-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-Sitzung | 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 Nachrichten-Warteschlange (vor PHP 8.0.0)
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore (vor PHP 8.0.0)
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory (vor PHP 8.0.0)
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX-Paket
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 (vor PHP 8.0.0)
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-komprimierte Datei
zlib.deflate | deflate_init() | deflate_add() | Nichts | inkrementeller Deflate-Kontext (vor PHP 8.0.0)
zlib.inflate | inflate_init() | inflate_add(), inflate_get_read_len(), inflate_get_status() | Nichts | inkrementeller Inflate-Kontext (vor PHP 8.0.0)

User Contributed Notes

Anonymous 28-Jul-2023 12:19
Resource of type "process" is returned by proc_open() and used by proc_close()


Liste verfügarer Filter

Inhaltsverzeichnis

  • Filter für Zeichenketten
  • Umwandlungsfilter
  • Komprimierungsfilter
  • Verschlüsselungsfilter

Im Folgenden sind einige eingebaute Stream-Filter aufgelistet, die mit der Funktion stream_filter_append() verwendet werden können. Je nach verwendeter PHP-Version gibt es möglicherweise mehr (oder weniger) Filter als die hier aufgeführten.

Es ist zu erwähnen, dass es eine leichte Asymmetrie zwischen den Funktionen stream_filter_append() und stream_filter_prepend() gibt. Jeder PHP-Stream enthält einen kleinen Lesepuffer, in dem er Datenblöcke speichert, die aus dem Dateisystem oder anderen Ressourcen abgerufen werden, um die Daten auf die effizienteste Weise zu verarbeiten. Wenn Daten aus der Ressource gezogen und in den internen Puffer des Streams geschoben werden, werden sie sofort durch alle damit verbundenen Filter verarbeitet, unabhängig davon, ob die PHP-Anwendung tatsächlich bereit ist für die Daten oder nicht. Wenn ein Filter angehängt wird, während sich Daten im Lesepuffer befinden, werden diese Daten sofort vom Filter verarbeitet. Das bedeutet, dass der Puffer transparent gehandhabt werden kann, also ohne dass man von dessen Existenz weiß. Wenn ein Filter jedoch vorangestellt wird, während Daten im Lesepuffer liegen, werden diese Daten NICHT durch diesen Filter verarbeitet. Es wird stattdessen gewartet, bis der nächste Datenblock von der Ressource abgerufen wird.

Mit der Funktion stream_get_filters() kann eine Liste der in der verwendeten PHP-Version installierten Filter abgerufen werden.

User Contributed Notes

There are no user contributed notes for this page.


Filter für Zeichenketten

Jeder dieser Filter tut genau das, was sein Name andeutet und entspricht dem Verhalten einer eingebauten php-Funktion zur Handhabung von Zeichenketten. Weitere Informationen zu einem bestimmten Filter sind auf der Handbuchseite der entsprechenden Funktion zu finden.

string.rot13

Die Verwendung dieses Filters entspricht der Verarbeitung aller Stream-Daten mit der Funktion str_rot13().

Beispiel #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Ausgabe: Guvf vf n grfg. */
?>

string.toupper

Die Verwendung dieses Filters entspricht der Verarbeitung aller Stream-Daten mit der Funktion strtoupper().

Beispiel #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Ausgabe: THIS IS A TEST. */
?>

string.tolower

Die Verwendung dieses Filters entspricht der Verarbeitung aller Stream-Daten mit der Funktion strtolower().

Beispiel #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Ausgabe: this is a test. */
?>

string.strip_tags

Die Verwendung dieses Filters entspricht der Verarbeitung aller Stream-Daten mit der Funktion strip_tags(). Er akzeptiert Parameter in einer von zwei Formen: entweder als Zeichenkette mit einer Liste von Tags, wie der zweite Parameter der Funktion strip_tags(), oder als Array von Tag-Namen.

Warnung

Dieses Feature ist seit PHP 7.3.0 als DEPRECATED (veraltet) markiert. Von der Verwendung dieses Features wird dringend abgeraten.

Beispiel #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>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Ausgabe: bolded text enlarged to a level 1 heading */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Ausgabe: bolded text enlarged to a level 1 heading */
?>

User Contributed Notes

There are no user contributed notes for this page.


Umwandlungsfilter

Wie die string.*-Filter führen auch die convert.*-Filter Aktionen aus, die ihren Namen entsprechen. Weitere Informationen zu einem bestimmten Filter sind auf der Handbuchseite für die entsprechende Funktion zu finden.

convert.base64-encode und convert.base64-decode

Die Verwendung dieser Filter entspricht der Verarbeitung aller Stream-Daten mit den Funktionen base64_encode() und base64_decode(). convert.base64-encode unterstützt Parameter, die als assoziatives Array übergeben werden. Wenn der Parameter line-length angegeben wird, wird die base64-Ausgabe in Abschnitte von line-length Zeichen aufgeteilt. Wenn der Parameter line-break-chars angegeben wird, werden die einzelnen Teilstücke durch die angegebenen Zeichen getrennt. Diese Parameter haben die gleiche Wirkung wie die Verwendung von base64_encode() in Verbindung mit chunk_split().

Beispiel #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Ausgabe: VGhpcyBpcyBhIHRlc3QuCg== */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Ausgabe: VGhpcyBp
: cyBhIHRl
: c3QuCg== */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Ausgabe: This is a test. */
?>

convert.quoted-printable-encode und convert.quoted-printable-decode

Die Verwendung der Decode-Version dieses Filters entspricht der Verarbeitung aller Stream-Daten mit der Funktion quoted_printable_decode(). Es gibt keine Funktion, die convert.quoted-printable-encode entspricht. convert.quoted-printable-encode unterstützt Parameter, die als assoziatives Array übergeben werden. Zusätzlich zu den Parametern, die von convert.base64-encode unterstützt werden, unterstützt convert.quoted-printable-encode auch die booleschen Parameter binary und force-encode-first. convert.base64-decode unterstützt nur den Parameter line-break-chars, der für die Zeilentrennung der kodierten Daten verwendet wird.

Beispiel #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Ausgabe: =This is a test.=0A */
?>

convert.iconv.*

Die convert.iconv.*-Filter sind verfügbar, wenn die iconv-Unterstützung aktiviert ist. Die Verwendung dieser Filter entspricht der Verarbeitung aller Stream-Daten mit der Funktion iconv(). Diese Filter unterstützen keine Parameter, sondern erwarten stattdessen, dass die Eingabe- und Ausgabekodierungen als Teil des Filternamens angegeben werden, d. h. entweder als convert.iconv.<input-encoding>.<output-encoding> oder als convert.iconv.<input-encoding>/<output-encoding> (beide Schreibweisen sind semantisch äquivalent).

Beispiel #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);
/* Ausgabe: 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.


Komprimierungsfilter

Während die Komprimierungs-Wrapper die Möglichkeit bieten, auf dem lokalen Dateisystem gzip- und bz2-kompatible Dateien zu erstellen, können sie weder mit komprimierten Netzwerkprotokollen umgehen, noch bieten sie eine Möglichkeit, einen unkomprimierten Stream zu erstellen und ihn dann zu komprimieren. Im Gegensatz dazu können Komprimierungsfilter jederzeit auf alle Stream-Ressourcen angewendet werden.

Hinweis: Komprimierungsfilter erzeugen keine Kopfzeilen und Anhänge (Trailer), wie sie von Kommandozeilenprogrammen wie gzip verwendet werden. Sie komprimieren und dekomprimieren nur die eigentlichen Nutzdaten innerhalb des Streams.

zlib.deflate und zlib.inflate

zlib.deflate (Komprimierung) und zlib.inflate (Dekomprimierung) sind Implementierungen der in » RFC 1951 beschriebenen Komprimierungsmethoden. Der deflate-Filter benötigt bis zu drei Parameter, die als assoziatives Array übergeben werden. level gibt die Komprimierungsstufe an, die verwendet werden soll (1-9). Je höher die Zahl, desto kleiner wird im Allgemeinen die Größe der komprimierten Daten, aber umso länger wird auch die Verarbeitungszeit. Es gibt auch zwei spezielle Komprimierungsstufen: 0 (keine Komprimierung) und -1 (die zlib-interne Voreinstellung - derzeit 6). window ist der Logarithmus zur Basis 2 für die Größe des Loopback-Fensters (der Speicherpuffer). Höhere Werte (bis zu 15 -- 32768 Bytes) ergeben eine bessere Komprimierung auf Kosten des Speichers, während niedrigere Werte (bis zu 9 -- 512 Bytes) eine schlechtere Komprimierung bei geringerem Speicherbedarf ergeben. Der derzeitige Standardwert für window ist 15. memory gibt an, wieviel Arbeitsspeicher zugewiesen werden soll. Die gültigen Werte reichen von 1 (minimale Zuweisung) bis 9 (maximale Zuweisung). Diese Speicherzuweisung wirkt sich nur auf die Geschwindigkeit aus und hat keinen Einfluss auf die Größe der komprimierten Daten.

Hinweis: Da die Komprimierungsstufe der am häufigsten verwendete Parameter ist, kann er auch als einfacher Integer-Wert statt als Array-Element angegeben werden.

Die zlib.*-Komprimierungsfilter sind verfügbar wenn die zlib-Unterstützung aktiviert ist.

Beispiel #1 zlib.deflate und zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Der Originaltext ist " . strlen($original_text) . " Zeichen lang.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "Die komprimierte Datei hat " . filesize('test.deflated') . " Bytes.\n";
echo "Der Originaltext war:\n";
/* Verwendung von readfile und zlib.inflate, um auf der Stelle zu dekomprimieren */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Erzeugt die Ausgabe:

Der Originaltext ist 70 Zeichen lang.
Die komprimierte Datei hat 56 Bytes.
Der Originaltext war:
This is a test.
This is only a test.
This is not an important string.

*/
?>

Beispiel #2 Vereinfachte Verwendung von zlib.deflate

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Der Originaltext ist " . strlen($original_text) . " Zeichen lang.\n";

$fp = fopen('test.deflated', 'w');
/* Hier steht "6" für die Komprimierungsstufe 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "Die komprimierte Datei hat " . filesize('test.deflated') . " Bytes.\n";

/* Erzeugt die Ausgabe:

Der Originaltext ist 70 Zeichen lang.
Die komprimierte Datei hat 56 Bytes.

*/
?>

bzip2.compress und bzip2.decompress

bzip2.compress und bzip2.decompress funktionieren auf die gleiche Weise wie die oben beschriebenen zlib-Filter. Der Filter bzip2.compress akzeptiert bis zu zwei Parameter, die als Elemente eines assoziativen Arrays angegeben werden: blocks ist ein ganzzahliger Wert von 1 bis 9, der die Anzahl der 100kB-Speicherblöcke angibt, die dem Arbeitsbereich zugewiesen werden sollen. work ist ebenfalls ein ganzzahliger Wert. Er reicht von 0 bis 250 und gibt an, wie viel Aufwand mit der normalen Komprimierungsmethode betrieben werden soll, bevor auf eine langsamere, aber zuverlässigere Methode zurückgegriffen wird. Wenn dieser Wert geändert wird, wirkt sich das nur auf die Geschwindigkeit der Komprimierung aus. Weder die Größe der komprimierten Ausgabe noch der Speicherverbrauch werden durch diese Einstellung verändert. Ein Wert von 0 bedeutet, dass die Bibliothek ihre Standardkonfiguration verwenden soll. Der Filter bzip2.decompress akzeptiert nur einen Parameter, der entweder als gewöhnlicher boolescher Wert oder als Element small eines assoziativen Arrays übergeben werden kann. Wenn small auf true gesetzt ist, wird die bzip-Bibliothek angewiesen, die Dekomprimierung auf Kosten der Geschwindigkeit mit minimalem Speicherplatzbedarf durchzuführen.

Die bzip2.*-Komprimierungsfilter sind verfügbar wenn die bz2-Unterstützung aktiviert ist.

Beispiel #3 bzip2.compress und bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "Die Originaldatei hat " . filesize('LICENSE') . " Bytes.";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "Die komprimierte Datei hat " . filesize('LICENSE.compressed') . " Bytes.\n";

/* Erzeugt die Ausgabe:

Die Originaldatei hat 3288 Bytes.
Die komprimierte Datei hat 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);


Verschlüsselungsfilter

Verschlüsselungsfilter sind besonders nützlich für die Verschlüsselung von Dateien/Streams.

mcrypt.* und mdecrypt.*

Warnung

Dieses Feature ist seit PHP 7.1.0 als DEPRECATED (veraltet) markiert. Von der Verwendung dieses Features wird dringend abgeraten.

mcrypt.* und mdecrypt.* ermöglichen mit Hilfe von libmcrypt die symmetrische Ver- und Entschlüsselung. Beide Gruppen von Filtern unterstützen die gleichen Algorithmen, die für die Erweiterung mcrypt in Form von mcrypt.ciphername zur Verfügung stehen, wobei ciphername der Name der Verschlüsselung ist, wie er auch an die Funktion mcrypt_module_open() übergeben werden würde. Die folgenden fünf Filterparameter sind ebenfalls verfügbar:

mcrypt-Filterparameter
Parameter | Erforderlich? | Standard | Beispielwerte
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Das Verzeichnis, das die Algorithmen enthält
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Das Verzeichnis, das die Modi enthält
iv | Required | N/A | Typischerweise 8, 16 oder 32 Byte Binärdaten. Abhängig von der Verschlüsselung
key | Required | N/A | Typischerweise 8, 16 oder 32 Byte Binärdaten. Abhängig von der Verschlüsselung

Beispiel #1 Ver- und Entschlüsselung mit Blowfish

<?php
// $key wird als zuvor generiert angenommen
$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, 'zu verschlüsselnede Nachricht');
fclose($fp);

// entschlüsseln...
$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)); // entfernt das Null-Padding
fclose($fp);
echo $data;
?>

Beispiel #2 Verschlüsseln einer Datei mit AES-128 CBC und SHA256 HMAC

<?php
AES_CBC::encryptFile($password, "klartext.txt", "verschluesselt.enc");
AES_CBC::decryptFile($password, "verschluesselt.enc", "entschluesselt.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']; } // Standard 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) ); // Platzhalter, hier wird später SHA256 HMAC eingefügt
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 ist eine Zahl von 1-16
fwrite($fc, str_repeat(chr($padding), $padding) ); // PKCS7-Padding durchführen
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); // Platzhalter überschreiben
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); // sha256 hmac und salt weglassen
$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]); // PKCS7-Padding wird angenommen
$block = substr($block, 0, 0-$padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2) {
if(strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
static $init=0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped=0;
function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped<32){
$outlen = min($bucket->datalen,32-$this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen-$outlen;
$this->skipped+=$outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}

User Contributed Notes

Maarten Bodewes 06-Aug-2017 12:21
The examples on this page should be destroyed with utmost urgency.

Strangely most people will fall over the use of generating the IV and 3DES key using MD5, a weak hash function, e.g. the previous note and CryptoFails blog.

http://www.cryptofails.com/post/70059608390/php-documentation-woes

A password based key derivation function should be used (bcrypt, PBKDF2).

However the use of MD-5 for key derivation however isn't that bad and if the password is strong enough (it usually isn't) then the generated DES ABC key is strong enough even now.

Using an identical IV for each password means that this function directly leaks information about the encrypted file. If the start of two encrypted files is identical then this function will directly leak information. For instance, if the routine encrypts multiple images then the JPEG header would be easily distinguished.

All in all these examples use deprecated routines (mcrypt), deprecated cryptographic functions (MD5 / DES) and then incorrectly perform the actual encryption. Enough reason to destroy them in the first place.
Uwe Ohse 22-Feb-2017 04:17
1) The mcrypt module has been deprecated with PHP 7.1.
What does that mean for the encryption filters?

2) deriving the IV from the secret passphrase seems wrong. This leaks information about the passphrase without need.

3) using md5() for this? Really? hash() has been available since PHP 5.1.2.

4) hashing the passphrase twice does not add any security.

5) using substr() on binary data (why, oh why, is true passed to md5()?) might lead to headaches if mbstring.func_overload is used.


Liste der unterstützten Socket-Transporter

Inhaltsverzeichnis

  • Internet Domain: TCP, UDP, SSL und TLS
  • Unix-Domain: Unix und UDG

Die folgende Liste enthält die verschiedenen URL-Varianten für Socket-Transporter, die in PHP integriert sind und mit den streambasierenden Socket-Funktionen wie fsockopen() und stream_socket_client() genutzt werden können. Diese Transporter beziehen sich nicht auf die Sockets-Erweiterung.

Eine Liste der in Ihrer PHP-Installation unterstützten Transporter erhalten Sie mit Hilfe der Funktion 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


Internet Domain: TCP, UDP, SSL und TLS

ssl://, tls://, sslv2:// & sslv3://.

Hinweis: Wird kein Transporter angegeben, so wird tcp:// angenommen.

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Internet-Domain-Sockets erwarten zusätzlich zur Zieladresse eine Portnummer. Im Fall von fsockopen() wird diese als zweiter Parameter übergeben und beeinflusst so nicht die Formatierung der Transporter-URL. Bei stream_socket_client() und damit zusammenhängenden Funktionen wird die Portnummer dagegen, wie in URLs üblich, von einem Doppelpunkt getrennt an den URL angehängt.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Hinweis: Numerische IPv6-Adressen mit Portnummern
Während im vorangegangenen Beispiel an die IPv4- und Hostname-Einträge nur der Doppelpunkt und die Portnummer angehängt wurden, ist die IPv6-Adresse in der zweiten Zeile zusätzlich in eckige Klammern gesetzt worden: [fe80::1]. Dies dient dazu, zwischen den Doppelpunkten in der IPv6-Adresse selbst und dem Trennzeichen zwischen Adresse und Portnummer unterscheiden zu können.

Die ssl://- und tls://-Transporter erweitern den tcp://-Transporter um SSL-Verschlüsselung (nur verfügbar, wenn PHP mit OpenSSL-Unterstützung kompiliert wurde).

ssl:// versucht je nach Fähigkeiten und Vorlieben des Kommunikationspartners eine SSL-V2- oder -V3-Verbindung herzustellen. sslv2:// und sslv3: erzwingen explizit die Nutzung des SSL-V2-bzw. -V3-Protokolls.

User Contributed Notes

christian at lantian dot eu 17-Sep-2013 12:46
@pablo dot livardo  :  I think that the problem you found is caused by the difference between the client/server encryption methods used.

The 465 port is used for SMTPS, and the server starts the encryption immediately it receives your connection. So, your code will work.

The 587 port is used for Submission (MSA or Mail Submission Agent) which works like the port 25. The server accepts your connection and doesn't activate the encryption. If you want an encrypted connection on the port 587, you must connect on it without encryption, you must start to dialog with the server (with EHLO) and after that you must ask the server to start the encrypted connection using the STARTTLS command. The server starts the encryption and now you can start as well the encryption on your client.

So, in few words, you can not use :

<?php $fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);  ?>

but you can use:

 <?php $fp = stream_socket_client("mail.example.com:587", $errno, $errstr); ?>

and after you send the STARTTLS command, you can enable the crypto:

<?php stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); ?>

P.S. My previous note on this page was totally wrong, so I ask the php.net admin to remove it.

:)
christian at lantian dot eu 16-Sep-2013 08:17
@pablo dot livardo  :  I think that the problem you found is caused by the difference between the client/server encryption methods used.

You tried to access the port 587 using TLS encryption, but the server uses the SSLv3 encryption on this port.

You can communicate with the Google server on port 465 because on this port the communication is encrypted using TLS and your client is configured to recognize the TLS.

So, if you want to connect on the Google server over the port 587, you simply must write:

<?php
$fp = fsockopen("ssl://mail.example.com", 587, $errno, $errstr);
?>

instead of:

<?php
$fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);
?>

:)
stefan at example dot com 20-Aug-2010 05:42
Actually, PHP is very able to start with an unencrypted connection and then switch to an encrypted one - refer to http://php.net/stream_socket_enable_crypto .
pablo dot livardo at gmail dot com 09-Dec-2009 09:56
I've been having a problem with a TLS connection.

<?php
$fp = fsockopen("tls://mail.example.com", 587, $errno, $errstr);
?>

Which gives me an error of:

SSL operation failed with code 1. OpenSSL Error messages: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number

I believe this is caused by PHP not being able to start with an unencrypted connection and then switch to encryption even though the functionality is built into OpenSSL.

For Google Mail users you can avoid this by using port 465 instead of 587.


Unix-Domain: Unix und UDG

unix:// und udg://.

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// bietet Zugriff auf Socket-Verbindungen in der Unix-Domäne. udg:// bietet eine auf dem User-Datagram-Protokoll basierende Alternative zu Unix-Domain-Sockets. protocol.

Unix-Domain-Sockets erwarten im Gegensatz zu Internet-Domain-Sockets keine Portnummer. Bei Nutzung der fsockopen()-Funktion sollte daher der zweite Parameter portno für diese immer als 0 übergeben werden.

Hinweis: Unix-Domain-Sockets werden unter Windows nicht unterstützt.

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.


Tabelle zu Typenvergleichen in PHP

Die folgenden Tabellen zeigen das Verhalten von Typen und Vergleichsoperatoren in PHP, sowohl für schwach und stark typisierte Vergleiche. Dieser Anhang steht im Zusammenhang mit dem Abschnitt zu Type juggling. Anregungen für diesen Abschnitt kamen aus verschiedenen Benutzerkommentaren und der Arbeit von » BlueShoes.

Bevor diese Tabellen verwendet werden ist es wichtig die Typen und ihre Bedeutungen zu verstehen. "42" ist zum Beispiel ein string, während 42 ein int ist. false ist ein bool, obwohl "false" ein string ist.

Hinweis:

HTML-Formulare übergeben keine integer, float oder boolesche Werte, sie übertragen strings. Um herauszufinden, ob ein string numerisch ist kann man is_numeric() verwenden.

Hinweis:

Wenn man einfach if ($x) verwendet, obwohl $x undefiniert ist, so wird ein Fehler der Stufe E_NOTICE erzeugt. Verwenden sie stattdessen empty() oder isset() und/oder initialisiere sie die verwendeten Variablen.

Hinweis:

Einige numerische Operationen können ein Ergebnis erzeugen, welches durch die Konstante NAN represäntiert wird. Jeder schwach oder stark typisierte Vergleich dieses Wertes mit beliebigen anderen Werten, einschließlich der Konstante selbst, außer mit true, wird false ergeben (d.h. NAN != NAN und NAN !== NAN). Beispiele für Operationen, die NAN ergeben sind u.a. sqrt(-1), asin(2), und acosh(0).

Vergleiche von $x mittels PHP-Funktionen
Ausdruck | 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 ist undefiniert | 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

Typschwache Vergleiche mittels ==
 | 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
* vor PHP 8.0.0 true.

Typstarke Vergleiche mittels ===
 | 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
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
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).
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);
}

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


Liste der Parsertoken

Verschiedene Teile der Sprache PHP werden intern durch Token dargestellt. Ein Codeschnipsel, der eine ungültige Folge von Token enthält, kann zu Fehlern wie dem folgenden führen: Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10.", wobei token == intern durch T_IS_EQUAL dargestellt wird.

In der folgenden Tabelle sind alle Token aufgelistet. Sie sind auch als PHP-Konstanten verfügbar.

Hinweis: Verwendung der T_* Konstanten

Der Wert von T_*-Konstanten wird basierend auf der zugrundeliegenden Parser-Infrastruktur von PHP automatisch erzeugt. Das bedeutet, dass sich der konkrete Wert eines Tokens zwischen zwei PHP-Versionen ändern kann. Damit eine gewisse Kompatibilität über mehrere PHP-Versionen gewährleistet ist, sollte sich Code daher niemals direkt auf die Original-T_*-Werte verlassen, die einer PHP-Version X.Y.Z entnommen wurden.

Um T_*-Konstanten über mehrere PHP-Versionen hinweg zu verwenden, können undefinierte Konstanten vom Benutzer mit einer geeigneten Strategie definiert werden (unter Verwendung großer Zahlen wie 10000), die sowohl mit den PHP-Versionen als auch mit den T_*-Werten funktioniert.

<?php
// Vor PHP 7.4.0 ist T_FN nicht definiert.
defined('T_FN') || define('T_FN', 10001);

Token
Token | Syntax | Referenz
T_ABSTRACT | abstract | Klassenabstraktion
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG | & | Type declarations (verfügbar seit PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG | & | Type declarations (verfügbar seit PHP 8.1.0)
T_AND_EQUAL | &= | Zuweisungsoperatoren
T_ARRAY | array() | array(), Arraysyntax
T_ARRAY_CAST | (array) | Typumwandlung
T_AS | as | foreach
T_ATTRIBUTE | #[ | Attribute (verfügbar seit PHP 8.0.0)
T_BAD_CHARACTER |  | Alle Zeichen unterhalb von ASCII 32 mit Ausnahme von \t (0x09), \n (0x0a) und \r (0x0d) (verfügbar seit PHP 7.4.0)
T_BOOLEAN_AND | && | Logische Operatoren
T_BOOLEAN_OR | || | Logische Operatoren
T_BOOL_CAST | (bool) or (boolean) | Typumwandlung
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Exceptions (Ausnahmen)
T_CLASS | class | Klassen und Objekte
T_CLASS_C | __CLASS__ | Magische Konstanten
T_CLONE | clone | Klassen und Objekte
T_CLOSE_TAG | ?> oder %> | Den HTML-Bereich der Datei verlassen
T_COALESCE | ?? | Vergleichsoperatoren
T_COALESCE_EQUAL | ??= | Zuweisungsoperatoren (verfügbar seit PHP 7.4.0)
T_COMMENT | // oder #, und /* */ | Kommentare
T_CONCAT_EQUAL | .= | Zuweisungsoperatoren
T_CONST | const | Klassenkonstanten
T_CONSTANT_ENCAPSED_STRING | "foo" oder 'bar' | Stringsyntax
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | komplexe Variablen-Interpolationssyntax
T_DEC | -- | Inkrement- bzw. Dekrementoperatoren
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | Magische Konstanten
T_DIV_EQUAL | /= | Zuweisungsoperatoren
T_DNUMBER | 0.12, etc | Gleitkommawerte
T_DO | do | do..while
T_DOC_COMMENT | /** */ | Kommentare im PHPDoc-Stil
T_DOLLAR_OPEN_CURLY_BRACES | ${ | komplexe Variablen-Interpolationssyntax
T_DOUBLE_ARROW | => | Arraysyntax
T_DOUBLE_CAST | (real), (double) or (float) | Typumwandlung
T_DOUBLE_COLON | :: | Siehe T_PAAMAYIM_NEKUDOTAYIM weiter unten
T_ECHO | echo | echo
T_ELLIPSIS | ... | Funktionsargumente
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | Konstanter Teil einer Zeichenkette mit Variablen
T_ENDDECLARE | enddeclare | declare, Alternative Syntax
T_ENDFOR | endfor | for, Alternative Syntax
T_ENDFOREACH | endforeach | foreach, Alternative Syntax
T_ENDIF | endif | if, Alternative Syntax
T_ENDSWITCH | endswitch | switch, Alternative Syntax
T_ENDWHILE | endwhile | while, Alternative Syntax
T_ENUM | enum | Enumerations (verfügbar seit PHP 8.1.0)
T_END_HEREDOC |  | Heredoc-Syntax
T_EVAL | eval() | eval()
T_EXIT | exit oder die | exit(), die()
T_EXTENDS | extends | extends, Klassen und Objekte
T_FILE | __FILE__ | Magische Konstanten
T_FINAL | final | Final-Schlüsselwort
T_FINALLY | finally | Exceptions (Ausnahmen)
T_FN | fn | Pfeilfunktionen (verfügbar seit PHP 7.4.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function | Funktionen
T_FUNC_C | __FUNCTION__ | Magische Konstanten
T_GLOBAL | global | Geltungsbereich von Variablen
T_GOTO | goto | goto
T_HALT_COMPILER | __halt_compiler() | __halt_compiler
T_IF | if | if
T_IMPLEMENTS | implements | Objekt-Interfaces (Schnittstellen)
T_INC | ++ | Inkrement- bzw. Dekrementoperatoren
T_INCLUDE | include | include
T_INCLUDE_ONCE | include_once | include_once
T_INLINE_HTML |  | Text außerhalb von PHP
T_INSTANCEOF | instanceof | Typoperatoren
T_INSTEADOF | insteadof | Traits
T_INTERFACE | interface | Objekt-Interfaces (Schnittstellen)
T_INT_CAST | (int) oder (integer) | Typumwandlung
T_ISSET | isset() | isset()
T_IS_EQUAL | == | Vergleichsoperatoren
T_IS_GREATER_OR_EQUAL | >= | Vergleichsoperatoren
T_IS_IDENTICAL | === | Vergleichsoperatoren
T_IS_NOT_EQUAL | != or <> | Vergleichsoperatoren
T_IS_NOT_IDENTICAL | !== | Vergleichsoperatoren
T_IS_SMALLER_OR_EQUAL | <= | Vergleichsoperatoren
T_LINE | __LINE__ | Magische Konstanten
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc | Integerwerte
T_LOGICAL_AND | and | Logische Operatoren
T_LOGICAL_OR | or | Logische Operatoren
T_LOGICAL_XOR | xor | Logische Operatoren
T_MATCH | match | match (verfügbar seit PHP 8.0.0)
T_METHOD_C | __METHOD__ | Magische Konstanten
T_MINUS_EQUAL | -= | Zuweisungsoperatoren
T_MOD_EQUAL | %= | Zuweisungsoperatoren
T_MUL_EQUAL | *= | Zuweisungsoperatoren
T_NAMESPACE | namespace | Namensräume
T_NAME_FULLY_QUALIFIED | \App\Namespace | Namensräume (verfügbar seit PHP 8.0.0)
T_NAME_QUALIFIED | App\Namespace | namespaces (verfügbar seit PHP 8.0.0)
T_NAME_RELATIVE | namespace\Namespace | namespaces (verfügbar seit PHP 8.0.0)
T_NEW | new | Klassen und Objekte
T_NS_C | __NAMESPACE__ | Namensräume
T_NS_SEPARATOR | \ | Namensräume
T_NUM_STRING | "$a[0]" | Numerischer Array-Index innerhalb einer Zeichenkette
T_OBJECT_CAST | (object) | Typumwandlung
T_OBJECT_OPERATOR | -> | Klassen und Objekte
T_NULLSAFE_OBJECT_OPERATOR | ?-> | Klassen und Objekte
T_OPEN_TAG | <?php, <? or <% | HTML-Bereich der Datei verlassen
T_OPEN_TAG_WITH_ECHO | <?= or <%= | HTML-Bereich der Datei verlassen
T_OR_EQUAL | |= | Zuweisungsoperatoren
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Auch definiert als T_DOUBLE_COLON.
T_PLUS_EQUAL | += | Zuweisungsoperatoren
T_POW | ** | Arithmetische Operatoren
T_POW_EQUAL | **= | Zuweisungsoperatoren
T_PRINT | print | print
T_PRIVATE | private | Klassen und Objekte
T_PROTECTED | protected | Klassen und Objekte
T_PUBLIC | public | Klassen und Objekte
T_READONLY | readonly | classes and objects (verfügbar seit PHP 8.1.0)
T_REQUIRE | require | require
T_REQUIRE_ONCE | require_once | require_once
T_RETURN | return | Rückgabe von Werten
T_SL | << | Bitweise Operatoren
T_SL_EQUAL | <<= | Zuweisungsoperatoren
T_SPACESHIP | <=> | Vergleichsoperatoren
T_SR | >> | Bitweise Operatoren
T_SR_EQUAL | >>= | Zuweisungsoperatoren
T_START_HEREDOC | <<< | Heredoc-Syntax
T_STATIC | static | Geltungsbereich von Variablen
T_STRING | parent, self, etc. | Dabei handelt es sich um Bezeichner, z. B. Schlüsselwörter wie parent und self, Funktionsnamen, Klassennamen usw. Vgl. T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | Typumwandlung
T_STRING_VARNAME | "${a | komplexe Variablen-Interpolationssyntax
T_SWITCH | switch | switch
T_THROW | throw | Exceptions (Ausnahmen)
T_TRAIT | trait | Traits
T_TRAIT_C | __TRAIT__ | __TRAIT__
T_TRY | try | Exceptions (Ausnahmen)
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | Typumwandlung
T_USE | use | Namensräume
T_VAR | var | Klassen und Objekte
T_VARIABLE | $foo | Variablen
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | Zuweisungsoperatoren
T_YIELD | yield | Generatoren
T_YIELD_FROM | yield from | Generator

Siehe auch token_name().

User Contributed Notes

daniel_rhodes at yahoo dot co dot uk 28-Mar-2024 08:41
In the above table of Tokens, it's worth noting that the bracketed text of "available as of PHP x.y.z" can mean one of two things:

[] This *parser token* is available as of PHP x.y.z
    {eg. T_BAD_CHARACTER, T_NAME_QUALIFIED}

[] This *language feature* is available as of PHP x.y.z
    {eg. T_ATTRIBUTE, T_COALESCE_EQUAL}
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.


Userland-Namensregeln

Inhaltsverzeichnis

  • Globaler Namensraum
  • Regeln
  • Tipps

Es folgen einige Vorgaben zur Namensgebung für Bezeichner in PHP Code. Diese Vorgaben sollten zumindest immer dann beachtet werden, wenn Code Symbole im globalen Namensraum anlegt, um Konflikte zwischen ihrem Code und zukünftigen Versionen von PHP zu vermeiden.

User Contributed Notes

There are no user contributed notes for this page.


Globaler Namensraum

Die folgende Liste bietet einen Überblick über die verschiedenen möglichen Programmkonstrukte im globalen Namensraum:

  • Funktionen

  • Klassen

  • Schnittstellen (interfaces)

  • Konstanten (aber keine Klassenkonstanten)

  • außerhalb von Funktionen oder Methoden definierte Variablen

User Contributed Notes

There are no user contributed notes for this page.


Regeln

Die folgende Liste gibt einen Überblick über die Rechte, die das PHP Projekt bei der Auswahl von Namen für neue interne Bezeichner für sich selbst in Anspruch nimmt. Die definitiven Vorgaben finden sich in den offiziellen » CODING STANDARDS:

  • PHP ist Eigentümer des globalen Namensraumes, versucht aber vernünftige sprechende Namen zu finden, und offensichtliche Konflikte zu vermeiden.

  • Funktionsnamen benutzten Unterstriche als Trennzeichen zwischen Wörtern, während Klassennamen den camelCase und PascalCase Regeln folgen.

  • PHP wird jedem globalen Symbol einer Erweiterung den Namen der Erweiterung voranstellen (in der Vergangenheit gab es allerdings zahlreiche Abweichungen von dieser Regel), z.B.:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (Beispiel einer früheren Abweichung)

    • new SplFileObject()

  • Bei Iteratoren und Ausnahmen wird dagegen einfach ein "Iterator" oder "Exception" an den Namen angehängt, z.B.:

    • ArrayIterator

    • LogicException

  • PHP reserviert alle Symbole, die mit zwei Unterstrichen __ beginnen, für interne Zwecke. Sie sollten nur dann Namen mit __ beginnen lassen, wenn Sie eine der dokumentierten "magischen" Funktionalitäten in PHP nutzen wollen, z.B:

    • __get()

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


Tipps

Um zukunftssicheren Code zu schreiben, wird empfohlen möglichst wenig Variablen, Funktionen oder Klassen im globalen Namensraum zu platzieren. Das wird Namenskonflikte mit Code von Drittanbietern sowie auch möglichen zukünftigen Erweiterung der Sprache verhindern.

Eine übliche Maßnahme, um Namenskonflikte von Funktionen und Klassen zu vermeiden, ist diese zu ihrem eigenen Namensraum hinzuzufügen.

<?php

namespace MyProject;

function my_function() {
return true;
}

\MyProject\my_function();

Das erfordert noch immer den Überblick über bereits verwendete Namesräume zu behalten, aber sobald entschieden wurde, welcher Namensraum verwendet werden soll, können diesem alle Funktionen und Klassen hinzugefügt werden, ohne weitere Gedanken an Konflikte verschwenden zu müssen.

Es wird als beste Praxis angesehen, die Zahl von Variablen, die zum globalen Geltungsbereich hinzugefügt werden, zu beschränken, um Namenskonflikte mit Code von Drittanbietern zu vermeiden.

Hinweis: Geltungsbereich von Variablen

Aufgrund der Geltungsbereichsregeln von PHP befinden sich Variablen, die in Funktionen oder Methoden definiert sind, nicht im globalen Geltungsbereich, und können daher nicht mit anderen Variablen, die im globalen Geltungsbereich definiert sind, kollidieren.

User Contributed Notes

There are no user contributed notes for this page.


Über das Handbuch

Inhaltsverzeichnis

  • Formate
  • Über die Kommentare (User Notes)
  • Wie man eine Funktionsdefinition (Prototyp) liest
  • In diesem Handbuch beschriebene PHP-Versionen
  • Mehr Informationen über PHP finden
  • Wie man helfen kann, die Dokumentation zu verbessern
  • Wie wir die Formate generieren
  • Übersetzungen

User Contributed Notes

There are no user contributed notes for this page.


Formate

Das PHP Handbuch wird in diversen Formaten zur Verfügung gestellt. Diese Formate lassen sich in zwei Gruppen aufteilen: Formate, die online lesbar sind und solche, die zum Download bereit stehen.

Hinweis:

Einige Verlage haben gedruckte Versionen dieses Handbuchs veröffentlicht. Wir können diese Bücher nicht empfehlen, da sie relativ schnell veraltet sind.

Sie können das Handbuch online auf der » PHP.net-Webseite. Die online lesbare Version des PHP-Handbuches besitzt derzeit zwei CSS-Stylesheets, ein Web-freundliches und ein Drucker-freundliches Stylesheet.

Die beiden Vorteile des Onlinehandbuchs gegenüber den meisten Offlineformaten sind die Integration von Kommentaren (User Notes), die von Usern eingetragen werden, sowie die » URL-Shortcuts, die verwendet werden können, um schnell zu den gewünschten Teilen des Handbuchs zu gelangen. Ein offensichtlicher Nachteil ist, dass Sie online sein müssen, um das Onlinehandbuch anzusehen.

Es stehen diverse Offlineformate des Handbuchs zur Verfügung. Welches Format das Beste für Sie ist hängt davon ab, welches Betriebssystem Sie verwenden und welches Sie am liebsten lesen. Wenn Sie Informationen darüber suchen, wie das Handbuch in so vielen verschiedenen Formaten generiert wird, lesen Sie bitte den Abschnitt 'Wie wir die Formate generieren' in diesem Anhang.

Das plattformunabhängigste Format des Handbuchs ist die HTML-Version. Diese steht sowohl als einzelne HTML-Datei, als auch als Paket von mehren einzelnen Dateien für jedes Kapitel (welches mehrere tausend Dateien ergibt) zur Verfügung. Wir bieten beide Versionen komprimiert an, weshalb ein Dekomprimierungsprogramm benötigt wird, um an die Dateien innerhalb der Archive zu gelangen.

Für die Windows-Plattformen verbessert die Windows HTML Help Version das HTML Format für die Benutzung in der Windows HTML Help Anwendung. Diese Version beinhaltet eine Volltextsuche, einen kompletten Index und Lesezeichen. Viele bekannte PHP Entwicklungsumgebungen haben diese Version der Dokumentation für schnelleren Zugriff integriert. Außerdem sind CHM Betrachter für Linux-Desktops verfügbar. Zum Beispiel » xCHM oder » GnoCHM.

Außerdem ist eine » erweiterte CHM version verfügbar, die weniger häufig aktualisiert wird, aber viele zusätzliche Features anbietet. Diese funktioniert allerdings aufgrund der Technologien, die für den Aufbau der Hilfeseiten verwendet werden, nur zusammen mit Microsoft Windows.

User Contributed Notes

There are no user contributed notes for this page.


Über die Kommentare (User Notes)

Die Kommentare der Benutzer spielen eine wichtige Rolle in der Entwicklung des Handbuchs. Dadurch, dass Benutzern erlaubt wird, Beispiele, Warnungen und weitere Klärungen über ihren Browser beizusteuern, ist es uns möglich, diese Rückmeldungen in den Text des Handbuchs einzuarbeiten. Und bis die Kommentare eingearbeitet sind können sie online und in manchen Offlineformaten in der Form eingesehen werden, wie sie eingetragen wurden.

Hinweis:

Die Kommentare sind nicht moderiert bevor sie online erscheinen, also kann für die Qualität des Schriftstils und der Codebeispiele, ja sogar für die Richigkeit der Beiträge, nicht garantiert werden. (Nicht, dass es irgendeine Garantie für die Qualität oder Richtigkeit des Handbuchs an sich gibt.)

Hinweis:

Im Bezug auf die Lizenz der benutzerkommentare werden diese als Teil des PHP Handbuches betrachtet und unterliegen daher der selben Lizenz, die auch für das handbuch gilt (zur Zeit "Creative Commons Attribution"). Für nähere Informationen siehe auch Copyright des Handbuchs

User Contributed Notes

There are no user contributed notes for this page.


Wie man eine Funktionsdefinition (Prototyp) liest

Jede Funktion im Handbuch ist für schnelles Nachschlagen dokumentiert. Zu wissen, wie man diesen Text liest und versteht, wird es viel einfacher machen, PHP zu lernen. Statt sich auf Beispiele und Auschneiden und Einfügen zu verlassen sollte jeder wissen, wie man eine Funktionsdefinition (Prototyp) liest. Lassen Sie uns anfangen:

Hinweis: Voraussetzung: Grundlegendes Verständnis der Typen

Obwohl PHP eine schwach typisierte Sprache ist, ist es wichtig, ein grundlegendes Verständnis von Typen zu besitzen, da sie eine wichtige Bedeutung haben.

Funktionsdefinitionen sagen uns, welcher Typ von Werten zurückgegeben wird. Lassen Sie uns die Definition von strlen() als unser erstes Beispiel nehmen:

strlen

(PHP 4, PHP 5, PHP 7)
strlen -- Ermitteln der String-Länge

Beschreibung
strlen ( string $string ) : int

Gibt die Länge der übergebenen Zeichenkette zurück.

Erklärung einer Funktionsdefinition
Teil | Beschreibung
strlen | Der Name der Funktion.
(PHP 4, PHP 5, PHP 7) | strlen() gab es in allen Versionen von PHP 4, 5 und PHP 7
( string $string ) | Der erste (und in diesem Fall einzige) Parameter (Argument) dieser Funktion trägt den Namen string und ist ein String.
int | Type des Wertes, den diese Funktion zurückgibt, welche hier ein int ist (d.h. die Länge einer Zeichenkette in Zahlen gemessen).

Wir könnten die oben angegebene Funktionsdefinition auf eine allgemeine Art umschreiben:

      Funktionsname    ( Parametertyp   Parametername ) : Rückgabetyp

Viele Funktionen akzeptieren mehrere Parameter, z. B. in_array(). Ihr Prototyp sieht wie folgt aus:

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

Was bedeutet das? in_array() liefert einen boolean-Wert zurück, true im Erfolgsfall (falls needle in haystack gefunden wurde)Bei einem Fehler wird false zurückgegeben. haystack gefunden wurde). Der erste Parameter heißt needle und kann viele verschiedene Typen annehmen, weshalb wir ihn "mixed" nennen. Diese mixed needle (wonach wir suchen) kann entweder ein skalarer Wert sein (string, integer oder float) oder ein array. haystack (das Array das wir durchsuchen) ist der zweite Parameter. Der dritte, optionale Parameter wird strict genannt. Alle optionalen Parameter haben Standardwerte; Wenn der Standardwert unbekannt ist, wird er als ? angezeigt. Das Handbuch erklärt, dass der Parameter strict den Standardwert false hat. Schauen Sie auf die Handbuchseite der jeweiligen Funktion, um nachzulesen, wie sie funktionieren.

Zusätzlich erlaubt das & (Kaufmanns-Und) Symbol, das einem Funktionsparameter vorangestellt wird, den Parameter als Referenz zu übergeben, wie hier zu sehen:

       preg_match ( string $pattern , string $subject , array &$matches = null,
       int $flags = 0 , int $offset = 0 ) : int|false

Diesem Beispiel kann entnommen werden, dass der dritte optionale Parameter &$matches als Referenz übergeben wird.

Es gibt auch Funktionen mit komplexeren PHP Versionsangaben. Nehmen wir html_entity_decode() als Beispiel:

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

Das heißt, die Funktion ist nur in PHP Versionen ab PHP 4.3.0 verfügbar.

User Contributed Notes

There are no user contributed notes for this page.


In diesem Handbuch beschriebene PHP-Versionen

Diese Dokumentation beinhaltet Informationen über aktuelle und zukünftige PHP-Versionen. Änderungen im Verhalten sind als Notizen, Changelogs und innerhalb des Textes der Handbuchseiten dokumentiert. Die älteste dokumentierte Version ist PHP 7.0.0.

Existiert Dokumentation für die neueste (unveröffentlichte) Entwicklungsversion von PHP, wird sie entweder als "verfügbar in Git" oder "Entwicklungsversion" bezeichnet. Und obwohl man diese Änderungen einplanen sollte, können sie sich in seltenen Fällen ändern.

Die gesamte Entwicklung findet in Git statt, und kann wie auf der Seite » anonymous Git access angegeben, ausgecheckt werden.

Zur Klarstellung: das Handbuch bezieht sich auf Haupt-, Neben- und Revisionsnummern der PHP-Releases. Zum Beispiel bezieht sich bei PHP 7.3.1 die 7 auf die Hautpversion, 3 auf die Nebenversion, und 1 auf die Revision. Typischerweise fügt PHP nur neue Features zu Haupt- und Nebenversionen, and behebt Fehler in Revisionen. Allerdings trifft diese Konvention nicht immer zu.

Es ist ebenfalls zu beachten, dass das PHP-Handbuch im Präsenz, und nicht im Futur geschrieben ist, selbst für dokumentierte Features, die noch nicht verfügbar sind. Dies ist dadurch begründet, dass das Handbuch so leichter die Zeit überdauern kann, so dass keine lästigen grammatikalischen Updates bei jeder neuen PHP-Version erforderlich sind.

Das PHP Handbuch gibt oft "Standardwerte" für PHP Direktiven an. Diese Werte basieren darauf, wie sich PHP ohne eine php.ini Konfigurationsdatei verhält, so dass sich dies von den Werten, die in den ausgelieferten php.ini-development und php.ini-production Dateien zu finden sind, unterscheiden kann. Sie beziehen sich auch auf die aktuellste Version von PHP, wobei Changelogeinträge ältere Werte erwähnen. Werfen Sie einen Blick in den Anhang zu PHP-Direktiven für Details zu diesen Werten und Änderungen daran.

User Contributed Notes

There are no user contributed notes for this page.


Mehr Informationen über PHP finden

Dieses Handbuch versucht nicht, Vorschriften über generelle Programmierpraktiken zu machen. Wer das erste mal programmiert oder Anfänger ist, könnte es schwer finden, PHP programmieren nur mit diesem Handbuch zu lernen. Suchen Sie sich lieber eine Anleitung, die auf Anfänger zugeschnitten ist.

Es gibt eine ganze Reihe von aktiven Mailinglisten, um über alle Aspekte der PHP-Programmierung zu diskutieren. Hängen Sie selber an einem Problem fest, erwägen Sie die Verwendung dieser Listen. Eine Liste von Hilfestellungen inklusive der Mailinglisten finden Sie auf der » PHP.net Unterstützungsseite.

User Contributed Notes

There are no user contributed notes for this page.


Wie man helfen kann, die Dokumentation zu verbessern

Es gibt mehrere Möglichkeiten, die jeder ergreifen kann, diese Dokumentation zu verbessern.

Wenn Sie einen Fehler in diesem Handbuch finden, egal in welcher Sprache, melden Sie ihn bitte über den Issue Tracker des Repositoriums der jeweiligen Sprache unter » https://github.com/php; Fehler im englischen Handbuch sollten zum Beispiel gemeldet werden unter » https://github.com/php/doc-en/issues. Alle die Dokumentation betreffenden Probleme, einschließlich solcher, die die Formate des Handbuchs betreffen, sollten als Fehlerberichte eingereicht werden.

Hinweis:

Bitte missbrauchen Sie die Issue Tracker nicht, indem Sie Hilfegesuche absenden. Verwenden Sie stattdessen eine der vielen » Unterstützungsoptionen.

Durch Kommentare kann jeder anderen Lesern zusätzliche Codebeispiele, Warnungen und weitere Klärungen zur Verfügung stellen. Aber tragen Sie bitte keine Bugreports in das Kommentarsystem ein. Mehr über die Kommentarfuntkion können Sie im Abschnitt 'Über die Kommentare (User Notes)' dieses Anhangs lesen.

Es ist auch möglich, Pull-Requests an den » GitHub-Spiegel des Dokumentations-Repositorys zu senden.

Das PHP Handbuch ist in viele Sprachen übersetzt. Wenn Sie Englisch und eine andere Sprachen beherrschen, dann können Sie das handbuch verbessern, indem Sie in einem Überstzungsteam mitarbeiten. Wollen Sie eine neue Übersetzung beginnen oder bei einem vorhandenen Übersetzungsteam beitreten, lesen Sie bitte » http://doc.php.net/tutorial/.

Das PHP Dokumentationsprojekt hat ebenfalls einen IRC Chatraum, in dem sich viele Autoren aufhalten. Schauen Sie doch mal in #php.doc auf irc.efnet.org vorbei und diskutieren Sie mit uns Wege, das Handbuch zu verbessern.

User Contributed Notes

There are no user contributed notes for this page.


Wie wir die Formate generieren

Dieses Handbuch ist in XML geschrieben, unter Verwendung der » DocBook XML DTD, und » PhD ([PH]P-basierender [D]okumentationsrenderer) für die Wartung und Formatierung.

Die Verwendung von XML als Quellformat bietet die Möglichkeit, aus den Quelldateien sehr viele verschiedene Formate zu generieren, während nur ein Quelldokument für alle Formate gepflegen werden muß. Das Programm für die Formatierung der online lesbaren Version des Handbuches ist » PhD. » Microsoft HTML Help Workshop wird dazu verwendet, das Handbuch im Windows HTML Help Format zu erzeugen und natürlich auch PHP selbst, um einige zusätzliche Konvertierungen und Formatierungen durchzuführen.

Das Handbuch wird in vielen Sprachen und Formaten erzeugt. Sehen Sie » https://www.php.net/docs.php für zusätzliche Details. Der XML-Quellcode kann von git heruntergeladen und unter » https://github.com/php/doc-de eingesehen werden. Die Dokumentation befinden sich im Modul phpdoc.

User Contributed Notes

There are no user contributed notes for this page.


Übersetzungen

Das PHP Handbuch ist nicht nur in verschiedenen Formaten, sondern auch in verschiedenen Sprachen verfügbar. Der Inhalt wird zuerst auf englisch geschrieben, bevor er von Teams auf der ganzen Welt in ihre Muttersprache übersetzt wird. Wenn die Übersetzung einer bestimmten Funktion oder eines Kapitels noch nicht abgeschlossen ist, so wird die englische Version angezeigt.

Die Personen, die an der Handbuchübersetzung mitwirken, beginnen mit dem XML Quellcode, von » https://github.com/php/doc-en und übersetzen diesen in ihre Muttersprache. Sie verwenden nicht die generierten Formate (wie HTML oder reinen Text), da sich das Build System sich um die Konvertierungen von XML in lesbare Formate kümmert.

Hinweis:

Wenn Sie bei der Übersetzung der Dokumentation mithelfen wollen, kontaktieren Sie bitte das Überetzungs- bzw. Dokumentationsteam, indem Sie die phpdoc Mailingliste abonnieren: Senden Sie eine Email an » phpdoc+subscribe@lists.php.net. Die Adresse der Mailingliste ist phpdoc@lists.php.net. Schreiben Sie, dass Sie interessiert sind, das Handbuch zu übersetzen und es wird sich sicher jemand bei Ihnen mit Feedback zum Anfangen einer neuen Überstzung melden oder das bestehenden Team für die gewünschte Sprache kontaktieren.

Im Moment ist das Handbuch (teilweise oder vollständig) in mehr als zehn Sprachen übersetzt.

Sämtliche Übersetzungen können hier heruntergeladen werden: » 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.


Verzeichnis der Inhaltsverzeichnisse

Inhaltsverzeichnis

  • Funktions- und Methodenverzeichnis
  • Verzeichnis der Beispiele

User Contributed Notes

There are no user contributed notes for this page.


Funktions- und Methodenverzeichnis

Verzeichnis aller Funktionen und Methoden im Handbuch

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 - Absolutwert bzw. Betrag
    • acos - Arkuskosinus
    • acosh - Areakosinus hyperbolikus
    • addcslashes - Stellt bestimmten Zeichen eines Strings ein "\" voran (wie in C)
    • addslashes - Stellt bestimmten Zeichen eines Strings ein "\" voran
    • AllowDynamicProperties::__construct - Erstellt eine neue Instanz des Attributs AllowDynamicProperties
    • apache_child_terminate - Beendet einen Apacheprozess nach der Anfrage
    • apache_getenv - Liefert eine Apache-Subprocess_env-Variable
    • apache_get_modules - Liefert eine Liste der geladenen Apachemodule
    • apache_get_version - Liefert die Apacheversion
    • apache_lookup_uri - Führt eine Teilanfrage für einen angegebenen URI durch und liefert alle Informationen darüber zurück
    • apache_note - Liefert und setzt Mitteilungen für Apache-Anfragen
    • apache_request_headers - Liefert alle HTTP-Requestheader
    • apache_response_headers - Liefert alle HTTP-Responseheader
    • apache_setenv - Setzt eine Apache-Subprocess_env-Variable
    • 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 - Erstellt ein Array
    • ArrayAccess::offsetExists - Prüft, ob ein Offset-Punkt existiert
    • ArrayAccess::offsetGet - Gibt den Wert eines Offset-Punkts zurück
    • ArrayAccess::offsetSet - Zuweisen eines Wertes an angegebenen Offset
    • ArrayAccess::offsetUnset - Löschen eines Offsets
    • ArrayIterator::append - Append an element
    • ArrayIterator::asort - Sort entries by values
    • ArrayIterator::count - Count elements
    • ArrayIterator::current - Return current array entry
    • ArrayIterator::getArrayCopy - Get array copy
    • ArrayIterator::getFlags - Get behavior flags
    • ArrayIterator::key - Return current array key
    • ArrayIterator::ksort - Sort entries by keys
    • ArrayIterator::natcasesort - Sort entries naturally, case insensitive
    • ArrayIterator::natsort - Sort entries naturally
    • ArrayIterator::next - Move to next entry
    • ArrayIterator::offsetExists - Check if offset exists
    • ArrayIterator::offsetGet - Get value for an offset
    • ArrayIterator::offsetSet - Set value for an offset
    • ArrayIterator::offsetUnset - Unset value for an offset
    • ArrayIterator::rewind - Rewind array back to the start
    • ArrayIterator::seek - Seek to position
    • ArrayIterator::serialize - Serialize
    • ArrayIterator::setFlags - Set behaviour flags
    • ArrayIterator::uasort - Sort with a user-defined comparison function and maintain index association
    • ArrayIterator::uksort - Sort by keys using a user-defined comparison function
    • ArrayIterator::unserialize - Unserialize
    • ArrayIterator::valid - Check whether array contains more entries
    • ArrayIterator::__construct - Construct an ArrayIterator
    • ArrayObject::append - 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 - Create a new iterator from an ArrayObject instance
    • ArrayObject::getIteratorClass - Gets the iterator classname for the ArrayObject
    • ArrayObject::ksort - Sort the entries by key
    • ArrayObject::natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • ArrayObject::natsort - Sort entries using a "natural order" algorithm
    • ArrayObject::offsetExists - Returns whether the requested index exists
    • ArrayObject::offsetGet - Returns the value at the specified index
    • ArrayObject::offsetSet - 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 - Ändert die Groß- oder Kleinschreibung aller Schlüssel in einem Array
    • array_chunk - Splittet ein Array in Teile auf
    • array_column - Liefert die Werte einer einzelnen Spalte eines Arrays
    • array_combine - Erzeugt ein Array, indem es ein Array für die Schlüssel und ein anderes für die Werte verwendet
    • array_count_values - Zählt die Vorkommen jedes einzelnen Wertes in einem Array
    • array_diff - Ermittelt die Unterschiede zwischen Arrays
    • array_diff_assoc - Berechnet den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung
    • array_diff_key - Berechnet den Unterschied zwischen Arrays, indem es die Schlüssel vergleicht
    • array_diff_uassoc - Berechnet den Unterschied von Arrays mit zusätzlicher Indexprüfung, welche durch eine benutzerdefinierte Callback-Funktion vorgenommen wird
    • array_diff_ukey - Berechnet den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Vergleich der Schlüssel
    • array_fill - Füllt ein Array mit Werten
    • array_fill_keys - Befüllt ein Array mit Werten mit den übergebenen Schlüsseln
    • array_filter - Filtert Elemente eines Arrays mittels einer Callback-Funktion
    • array_flip - Vertauscht alle Schlüssel mit ihren zugehörigen Werten in einem Array
    • array_intersect - Ermittelt die Schnittmenge von Arrays
    • array_intersect_assoc - Ermittelt die Schnittmenge von Arrays mit zusätzlicher Indexprüfung
    • array_intersect_key - Ermittelt die Schnittmenge von Arrays, indem es die Schlüssel vergleicht
    • array_intersect_uassoc - Ermittelt die Schnittmenge von Arrays mit Indexprüfung; vergleicht Indizes mit einer Callbackfunktion
    • array_intersect_ukey - Ermittelt die Schnittmenge zweier Arrays mittels eines durch eine Callbackfunktion durchgeführten Schlüsselvergleiches
    • array_is_list - Prüft, ob das angegebene Array eine Liste ist
    • array_keys - Liefert alle Schlüssel oder eine Teilmenge aller Schlüssel eines Arrays
    • array_key_exists - Prüft, ob ein gegebener Schlüssel in einem Array existiert
    • array_key_first - Ermittelt den ersten Schlüssel eines Arrays
    • array_key_last - Ermittelt den letzten Schlüssel eines Arrays
    • array_map - Wendet eine Callback-Funktion auf die Elemente von Arrays an
    • array_merge - Führt zwei oder mehr Arrays zusammen
    • array_merge_recursive - Führt ein oder mehrere Arrays rekursiv zusammen
    • array_multisort - Sortiert mehrere oder multidimensionale Arrays
    • array_pad - Füllt ein Array bis auf die angegebene Länge mit einem Wert auf
    • array_pop - Liefert und entfernt das letzte Element eines Arrays
    • array_product - Ermittelt das Produkt der Werte eines Arrays
    • array_push - Fügt ein oder mehr Elemente an das Ende eines Arrays an
    • array_rand - Liefert einen oder mehrere zufällige Schlüssel eines Arrays
    • array_reduce - Reduziert das Array mittels einer Callback-Funktion iterativ auf einen einzigen Wert
    • array_replace - Ersetzt Elemente von übergebenen Arrays im ersten Array
    • array_replace_recursive - Ersetzt rekursiv Elemente des ersten Arrays durch Elemente der übergebenen Arrays
    • array_reverse - Liefert ein Array mit umgekehrter Reihenfolge der Elemente
    • array_search - Durchsucht ein Array nach einem Wert und liefert bei Erfolg den zugehörigen Schlüssel
    • array_shift - Liefert und entfernt das erste Element eines Arrays
    • array_slice - Extrahiert einen Ausschnitt eines Arrays
    • array_splice - Entfernt einen Teil eines Arrays und ersetzt ihn durch etwas anderes
    • array_sum - Liefert die Summe der Werte eines Array
    • array_udiff - Ermittelt den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Datenvergleich
    • array_udiff_assoc - Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht mittels einer Callbackfunktion
    • array_udiff_uassoc - Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht Daten und Indizes mittels einer Callbackfunktion
    • array_uintersect - Ermittelt die Schnittmenge von Arrays, vergleicht Daten mittels einer Callbackfunktion
    • array_uintersect_assoc - Ermittelt die Schnittmenge von Arrays mit zusätzlicher Indexprüfung, vergleicht Daten mittels einer Callbackfunktion
    • array_uintersect_uassoc - Ermittelt die Schnittmenge von Arrays mit zusätzlicher Indexprüfung, vergleicht Daten und Schlüssel mittels separaten Callbackfunktionen
    • array_unique - Entfernt doppelte Werte aus einem Array
    • array_unshift - Fügt ein oder mehr Elemente am Anfang eines Arrays ein
    • array_values - Liefert alle Werte eines Arrays
    • array_walk - Wendet eine vom Benutzer gelieferte Funktion auf jedes Element eines Arrays an
    • array_walk_recursive - Wendet eine Benutzerfunktion rekursiv auf jedes Element eines Arrays an
    • arsort - Sortiert ein Array in absteigender Reihenfolge und behält die Indexzuordnung bei
    • asin - Arkussinus
    • asinh - Areasinus hyperbolikus
    • asort - Sortiert ein Array in aufsteigender Reihenfolge und behält die Indexzuordnung bei
    • assert - Überprüft eine Assertion (Zusicherung)
    • assert_options - Setzt oder liefert Assert-Optionen
    • atan - Arkustangens
    • atan2 - Arkustangens-Variante mit zwei Parametern
    • atanh - Areatangens hyperbolikus
    • Attribute::__construct - Erstellt eine neue Instanz von Attribute
  • b
    • BackedEnum::from - Ordnet einen Skalar einer Enum-Instanz zu
    • BackedEnum::tryFrom - Ordnet einen Skalar einer Enum-Instanz oder null zu
    • base64_decode - Dekodiert MIME base64-kodierte Daten
    • base64_encode - Kodiert Daten MIME base64
    • basename - Liefert den letzten Namensteil einer Pfadangabe
    • BaseResult::getWarnings - Ruft Warnungen der letzten Operation ab
    • BaseResult::getWarningsCount - Ruft die Anzahl der Warnungen der letzten Operation ab
    • base_convert - Wandelt einen numerischen Wert zwischen verschiedenen Zahlensystemen um
    • bcadd - Addition zweier Zahlen beliebiger Genauigkeit
    • bccomp - Vergleich zweier Zahlen beliebiger Genauigkeit
    • bcdiv - Division zweier Zahlen beliebiger Genauigkeit
    • bcmod - Modulo zweier Zahlen mit beliebiger Genauigkeit
    • bcmul - Multiplikation zweier Zahlen beliebiger Genauigkeit
    • bcpow - Potenz einer Zahl beliebiger Genauigkeit
    • bcpowmod - Potenz einer Zahl beliebiger Genauigkeit, vermindert um ein angegebenen Modulo
    • bcscale - Setzt oder holt die Genauigkeit aller BCmath-Funktionen
    • bcsqrt - Ermittelt die Quadratwurzel einer Zahl beliebiger Genauigkeit
    • bcsub - Subtrahiert zwei Zahlen beliebiger Genauigkeit
    • bin2hex - Wandelt Binär-Daten in ihre hexadezimale Entsprechung um
    • bindec - Wandelt von binär zu dezimal um
    • bindtextdomain - Setzt oder liefert den Pfad für eine Domain
    • bind_textdomain_codeset - Setzt oder liefert den Zeichensatz der Meldungen, die aus der Übersetzungstabelle der DOMAIN zurückgegeben werden
    • boolval - Get the boolean value of a variable
    • bzclose - Schließt eine bzip2-Datei
    • bzcompress - Komprimiert eine Zeichenkette in bzip2-encodierte Daten
    • bzdecompress - Dekomprimiert bzip2-kodierte Daten
    • bzerrno - Gibt eine bzip2-Fehlernummer zurück
    • bzerror - Gibt die bzip2-Fehlernummer und die -Fehlermeldung in einem Array zurück
    • bzerrstr - Gibt eine bzip2-Fehlermeldung zurück
    • bzflush - Nichts tun
    • bzopen - Öffnet eine bzip2-komprimierte Datei
    • bzread - Binär-sicheres Lesen aus einer bzip2-Datei
    • bzwrite - Binär-sicheres Schreiben einer bzip2-Datei
  • 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 - Ruft die Callback-Funktion auf, die als erster Parameter übergeben wurde
    • call_user_func_array - Call a callback with an array of parameters
    • cal_days_in_month - Gibt die Anzahl der Tage eines bestimmten Monats in einem bestimmten Jahr in einem bestimmten Kalender zurück
    • cal_from_jd - Konvertiert von Julian Day Count zu einem unterstützten Kalender
    • cal_info - Gibt Informationen zu einem bestimmten Kalender zurück
    • cal_to_jd - Konvertiert von einem unterstützten Kalenderformat in Julian-Format
    • ceil - Rundet Brüche auf
    • chdir - Wechseln des Verzeichnisses
    • checkdate - Prüft ein Gregorianisches Datum auf Gültigkeit
    • checkdnsrr - Prüft DNS-Einträge auf Übereinstimmung mit einem gegebenen Internet-Hostnamen oder einer IP-Adresse
    • chgrp - Ändert die Gruppenzugehörigkeit einer Datei
    • chmod - Ändert den Modus für die Zugriffsrechte einer Datei
    • chop - Alias von rtrim
    • chown - Ändert den Eigentümer einer Datei
    • chr - Erzeugt eine Ein-Byte-Zeichenkette aus einer Zahl
    • chroot - Wechselt das Wurzelverzeichnis
    • chunk_split - Zerlegt einen String in Teile gleicher Länge
    • class_alias - Erzeugt einen Alias für eine Klasse
    • class_exists - Prüft, ob eine bestimmte Klasse definiert wurde
    • 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 - Löscht den Status-Cache
    • Client::getClient - Ruft eine Client-Session ab
    • Client::__construct - Der Konstruktor der Klasse Client
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - Schließt ein Verzeichnis-Handle
    • closelog - Schließt die Verbindung zum System-Logger
    • Closure::bind - Dupliziert eine Closure mit einem bestimmten gebundenen Objekt und Geltungsbereich einer Klasse
    • Closure::bindTo - Dupliziert eine Closure mit einem neuen gebundenen Objekt und Geltungsbereich einer Klasse
    • Closure::call - Bindet eine Closure und ruft sie auf
    • Closure::fromCallable - Wandelt ein Callable in eine Closure um
    • Closure::__construct - Konstruktor, der keine Instanziierung zulässt
    • 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 - Fügt einer Sammlung Dokumente hinzu
    • Collection::addOrReplaceOne - Fügt einer Sammlung ein Dokument hinzu oder ersetzt es
    • Collection::count - Ermittelt die Anzahl der Dokumente
    • Collection::createIndex - Erzeugt einen Index für die Sammlung
    • Collection::dropIndex - Löscht den Index einer Sammlung
    • Collection::existsInDatabase - Prüft, ob es die Sammlung in der Datenbank gibt
    • Collection::find - Sucht nach Dokumenten
    • Collection::getName - Ruft den Namen einer Sammlung ab
    • Collection::getOne - Ruft ein Dokument ab
    • Collection::getSchema - Ruft ein Schema-Objekt ab
    • Collection::getSession - Ruft ein Session-Objekt ab
    • Collection::modify - Ändert Dokumente einer Sammlung
    • Collection::remove - Löscht Dokumente einer Sammlung
    • Collection::removeOne - Löscht ein Dokument einer Sammlung
    • Collection::replaceOne - Ersetzt ein Dokument einer Sammlung
    • Collection::__construct - Der Konstruktor der Klasse Collection
    • CollectionAdd::execute - Führt eine Anweisung aus
    • CollectionAdd::__construct - Der Konstruktor der Klasse CollectionAdd
    • CollectionFind::bind - Bindet einen Wert an den Platzhalter einer Abfrage
    • CollectionFind::execute - Führt eine Anweisung aus
    • CollectionFind::fields - Setzt den Filter für die Felder eines Dokuments
    • CollectionFind::groupBy - Setzt die Kriterien für die Gruppierung
    • CollectionFind::having - Setzt Bedingungen für Aggregatfunktionen
    • CollectionFind::limit - Begrenzt die Anzahl der zurückgegebenen Dokumente
    • CollectionFind::lockExclusive - Führt eine Operation mit EXCLUSIVE LOCK aus
    • CollectionFind::lockShared - Führt eine Operation mit SHARED LOCK aus
    • CollectionFind::offset - Überspringt die angegebene Anzahl von Elementen, die zurückgegeben werden sollen
    • CollectionFind::sort - Setzt die Kriterien für die Sortierung
    • CollectionFind::__construct - Der Konstruktor der Klasse CollectionFind
    • CollectionModify::arrayAppend - Hängt ein Element an das Array eines Feldes an
    • CollectionModify::arrayInsert - Fügt ein Element in das Array eines Feldes ein
    • CollectionModify::bind - Bindet einen Wert an einen Platzhalter einer Abfrage
    • CollectionModify::execute - Führt eine Änderungsoperation aus
    • CollectionModify::limit - Begrenzt die Anzahl der zu ändernden Dokumente
    • CollectionModify::patch - Patcht ein Dokument
    • CollectionModify::replace - Ersetzt ein Feld eines Dokuments
    • CollectionModify::set - Setzt ein Attribut eines Dokuments
    • CollectionModify::skip - Überspringt Elemente
    • CollectionModify::sort - Setzt die Kriterien für die Sortierung
    • CollectionModify::unset - Löscht den Wert eines Feldes in einem Dokument
    • CollectionModify::__construct - Der Konstruktor der Klasse CollectionModify
    • CollectionRemove::bind - Bindet einen Wert an einen Platzhalter
    • CollectionRemove::execute - Führt eine Löschoperation aus
    • CollectionRemove::limit - Begrenzt die Anzahl der zu löschenden Dokumente
    • CollectionRemove::sort - Setzt die Kriterien für die Sortierung
    • CollectionRemove::__construct - Der Konstruktor der Klasse CollectionRemove
    • ColumnResult::getCharacterSetName - Ruft den Zeichensatz einer Spalte ab
    • ColumnResult::getCollationName - Ruft den Namen der Sortierreihenfolge einer Spalte ab
    • ColumnResult::getColumnLabel - Ruft den Bezeichner (Label) einer Spalte ab
    • ColumnResult::getColumnName - Ruft den Namen einer Spalte ab
    • ColumnResult::getFractionalDigits - Ruft die Anzahl der Nachkommastellen einer Spalte ab
    • ColumnResult::getLength - Ruft die Länge eines Spaltenfeldes ab
    • ColumnResult::getSchemaName - Ruft den Namen des Schemas einer Spalte ab
    • ColumnResult::getTableLabel - Ruft den Bezeichner (Label) der Tabelle einer Spalte ab
    • ColumnResult::getTableName - Ruft den Namen der Tabelle einer Spalte ab
    • ColumnResult::getType - Ruft den Typ einer Spalte ab
    • ColumnResult::isNumberSigned - Prüft, ob der Typ einer Spalte vorzeichenbehaftet ist
    • ColumnResult::isPadded - Prüft, ob eine Spalte aufgefüllt wird
    • ColumnResult::__construct - Der Konstruktor der Klasse ColumnResult
    • com::__construct - Der com-Klassenkonstruktor
    • 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 - Erstellt ein Array mit Variablen und deren Werten
    • 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 - Lädt eine 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 - Überprüft, ob die Verbindung zum Client beendet wurde
    • connection_status - Liefert den Verbindungsstatus als Bitfeld
    • constant - Liefert den Wert einer Konstante
    • convert_cyr_string - Konvertiert Strings von einem kyrillischen Zeichensatz in einen anderen
    • convert_uudecode - Dekodiert eine UU-kodierte Zeichenkette
    • convert_uuencode - UU-kodiert eine Zeichenkette
    • copy - Kopiert eine Datei
    • cos - Kosinus
    • cosh - Kosinus hyperbolikus
    • count - Zählt alle Elemente eines Arrays oder eines Countable-Objekts
    • Countable::count - Zählt die Elemente eines Objekts
    • count_chars - Gibt Informationen über die in einem String enthaltenen Zeichen zurück
    • crc32 - Berechnet den polynomischen CRC32-Wert eines Strings
    • create_function - Erzeugt eine Funktion dynamisch durch Auswertung einer Zeichenkette mit Code
    • CrudOperationBindable::bind - Bindet einen Wert an einen Platzhalter
    • CrudOperationLimitable::limit - Begrenzt die Anzahl der Ergebnisse
    • CrudOperationSkippable::skip - Überspringt die angegebene Anzahl von Datensätzen
    • CrudOperationSortable::sort - Sortiert die Ergebnisse
    • crypt - Einweg-String-Hashing
    • ctype_alnum - Prüft auf alphanumerische Zeichen
    • ctype_alpha - Prüft auf Buchstabe(n)
    • ctype_cntrl - Prüft auf Steuerzeichen
    • ctype_digit - Prüft auf Ziffern
    • ctype_graph - Prüft auf druckbare Zeichen (außer Leerzeichen)
    • ctype_lower - Prüft auf Kleinbuchstaben
    • ctype_print - Prüft auf druckbare Zeichen
    • ctype_punct - Prüft auf Sonderzeichen, d. h. auf druckbare Zeichen die weder Buchstaben noch Ziffern noch Leerzeichen sind.
    • ctype_space - Prüft auf Leerzeichen
    • ctype_upper - Prüft auf Großbuchstaben
    • ctype_xdigit - Prüft auf Zeichen, die eine Hexadezimalziffer darstellen
    • 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 - Ermittelt den Dateinamen
    • CURLFile::getMimeType - Ermittelt den Mime-Typ
    • CURLFile::getPostFilename - Ermittelt den Dateinamen für POST
    • CURLFile::setMimeType - Legt den Mime-Typ fest
    • CURLFile::setPostFilename - Legt den Dateinamen für POST fest
    • CURLFile::__construct - Erstellt ein CURLFile-Objekt
    • CURLStringFile::__construct - Erstellt ein CURLStringFile-Objekt
    • curl_close - Beendet eine cURL-Session
    • curl_copy_handle - Kopiert ein cURL-Handle inklusive aller Voreinstellungen
    • curl_errno - Gibt die letzte Fehlernummer zurück
    • curl_error - Gibt einen String zurück, der den letzten Fehler der aktuellen Session enthält
    • curl_escape - URL-kodiert den angegebenen String
    • curl_exec - Eine cURL-Session ausführen
    • curl_getinfo - Ruft Informationen zu einem bestimmten Transfer ab
    • curl_init - Initialisiert eine cURL-Session
    • curl_multi_add_handle - Fügt ein reguläres cURL-Handle einem cURL-Multi-Handle hinzu
    • curl_multi_close - Schließt eine Gruppe von cURL-Handles
    • curl_multi_errno - Gibt die Fehlernummer der letzten cURL-Multihandle-Operation zurück
    • curl_multi_exec - Führt die Unter-Verbindungen des cURL-Handles aus
    • curl_multi_getcontent - Liefert den Inhalt des cURL-Handles, falls CURLOPT_RETURNTRANSFER gesetzt ist
    • curl_multi_info_read - Informationen über die aktuellen Transfers abrufen
    • curl_multi_init - Liefert ein cURL-Mehrfach-Handle
    • curl_multi_remove_handle - Einen Multi-Handle von einer Menge aus cURL-Handles entfernen
    • curl_multi_select - Alle Sockets abfragen, die mit der cURL Erweiterung assoziiert sind und ausgewählt werden können
    • curl_multi_setopt - Setzt eine cURL-Multi-Option
    • curl_multi_strerror - Gibt einen String zurück, der den angegebenen Fehlercode beschreibt
    • curl_pause - Pausiert und setzt eine Verbindung fort
    • curl_reset - Setzt alle Optionen eines libcurl-Session-Handles zurück
    • curl_setopt - Setzt eine Option für einen cURL-Transfer
    • curl_setopt_array - Mehrere Optionen für einen cURL-Transfer setzen
    • curl_share_close - Schließt einen cURL-Share-Handle
    • curl_share_errno - Gibt die Fehlernummer der letzten cURL-Share-Operation zurück
    • curl_share_init - Initialisiert einen cURL-Share-Handle
    • curl_share_setopt - Setzt eine Option für einen cURL-Share-Handle
    • curl_share_strerror - Gibt einen String zurück, der den angegebenen Fehlercode beschreibt
    • curl_strerror - Gibt einen String zurück, der den angegebenen Fehlercode beschreibt
    • curl_unescape - Dekodiert die angegebene URL-kodierte Zeichenkette
    • curl_upkeep - Führt alle Prüfungen zur Aufrechterhaltung einer Verbindung durch
    • curl_version - Liefert die cURL-Version
    • current - Liefert das aktuelle Element eines Arrays
  • d
    • data:// - Data (RFC 2397)
    • DatabaseObject::existsInDatabase - Prüft, ob es das Objekt in der Datenbank gibt
    • DatabaseObject::getName - Ruft den Namen eines Objekts ab
    • DatabaseObject::getSession - Ruft den Namen einer Session ab
    • date - Formatiert einen Unix-Zeitstempel
    • DateInterval::createFromDateString - Bildet ein DateInterval aus relativen Teilen eines Strings
    • DateInterval::format - Formatiert ein Intervall
    • DateInterval::__construct - Erstellt ein neues DateInterval-Objekt
    • DatePeriod::createFromISO8601String - Erstellt ein neues DatePeriod-Objekt aus einer ISO8601-Zeichenkette
    • DatePeriod::getDateInterval - Liefert ein Intervall
    • DatePeriod::getEndDate - Liefert das Enddatum
    • DatePeriod::getRecurrences - Liefert die Anzahl der Wiederholungen
    • DatePeriod::getStartDate - Liefert das Startdatum
    • DatePeriod::__construct - Erstellt ein neues DatePeriod-Objekt
    • DateTime::add - Ändert ein DateTime-Objekt, wobei die Anzahl der Tage, Monate, Jahre, Stunden, Minuten und Sekunden hinzugefügt wird
    • DateTime::createFromFormat - Wertet eine Zeitangabe gemäß dem angegebenen Format aus
    • DateTime::createFromImmutable - Liefert eine neue DateTime-Instanz, die das angegebene DateTimeImmutable-Objekt kapselt
    • DateTime::createFromInterface - Liefert ein neues DateTime-Objekt, das das angegebene DateTimeInterface-Objekt kapselt
    • DateTime::getLastErrors - Alias von DateTimeImmutable::getLastErrors
    • DateTime::modify - Ändert den Zeitstempel
    • DateTime::setDate - Legt das Datum fest
    • DateTime::setISODate - Legt das ISO-Datum fest
    • DateTime::setTime - Legt die Uhrzeit fest
    • DateTime::setTimestamp - Legt Datum und Zeit basierend auf einem Unix-Zeitstempel fest
    • DateTime::setTimezone - Legt die Zeitzone für ein DateTime-Objekt fest
    • DateTime::sub - Subtrahiert eine Anzahl von Tagen, Monaten, Jahren, Stunden, Minuten und Sekunden von einem DateTime-Objekt.
    • DateTime::__construct - Liefert ein neues DateTime-Objekt
    • DateTime::__set_state - Der __set_state-Handler
    • DateTime::__wakeup - Der __wakeup-Handler
    • DateTimeImmutable::add - Liefert ein neues Objekt, bei dem eine Anzahl von Tagen, Monaten, Jahren, Stunden, Minuten und Sekunden zu einem bestehenden Objekt addiert wurde
    • DateTimeImmutable::createFromFormat - Wertet eine Zeitangabe gemäß dem angegebenen Format aus
    • DateTimeImmutable::createFromInterface - Liefert ein neues DateTimeImmutable-Objekt, das das angegebene DateTimeInterface-Objekt kapselt
    • DateTimeImmutable::createFromMutable - Liefert eine neue DateTimeImmutable-Instanz, die das angegebene DateTime-Objekt kapselt
    • DateTimeImmutable::getLastErrors - Liefert die Warnungen und Fehler
    • DateTimeImmutable::modify - Erzeugt ein neues Objekt mit geändertem Zeitstempel
    • DateTimeImmutable::setDate - Legt das Datum fest
    • DateTimeImmutable::setISODate - Legt das ISO-Datum fest
    • DateTimeImmutable::setTime - Legt die Uhrzeit fest
    • DateTimeImmutable::setTimestamp - Legt das Datum und die Uhrzeit basierend auf einem Unix-Zeitstempel fest
    • DateTimeImmutable::setTimezone - Legt die Zeitzone fest
    • DateTimeImmutable::sub - Subtrahiert eine Anzahl von Tagen, Monaten, Jahren, Stunden, Minuten und Sekunden
    • DateTimeImmutable::__construct - Liefert ein neues DateTimeImmutable-Objekt
    • DateTimeImmutable::__set_state - Der __set_state-Handler
    • DateTimeInterface::diff - Liefert die Differenz zwischen zwei DateTime-Objekten
    • DateTimeInterface::format - Liefert das Datum formatiert gemäß dem angegebenen Format
    • DateTimeInterface::getOffset - Liefert die Zeitverschiebung
    • DateTimeInterface::getTimestamp - Liefert den Unix-Zeitstempel
    • DateTimeInterface::getTimezone - Liefert die Zeitzone relativ zur angegebenen DateTime
    • DateTimeZone::getLocation - Liefert Standortinformationen zu einer Zeitzone
    • DateTimeZone::getName - Liefert den Namen einer Zeitzone
    • DateTimeZone::getOffset - Liefert die Zeitverschiebung gegenüber der GMT
    • DateTimeZone::getTransitions - Liefert alle Übergänge einer Zeitzone
    • DateTimeZone::listAbbreviations - Liefert ein assoziatives Array mit dst, offset und dem Namen der Zeitzone
    • DateTimeZone::listIdentifiers - Liefert ein numerisch indiziertes Array, das alle definierten Bezeichner der Zeitzonen enthält
    • DateTimeZone::__construct - Erstellt neues DateTimeZone-Objekt
    • date_add - Alias von DateTime::add
    • date_create - Erstellt ein neues DateTime-Objekt
    • date_create_from_format - Alias von DateTime::createFromFormat
    • date_create_immutable - Erstellt ein neues DateTimeImmutable-Objekt
    • date_create_immutable_from_format - Alias von DateTimeImmutable::createFromFormat
    • date_date_set - Alias von DateTime::setDate
    • date_default_timezone_get - Ermittelt die Standardzeitzone, die von allen Datums- und Zeitfunktionen in einem Skript verwendet wird
    • date_default_timezone_set - Setzt die Standardzeitzone, die von allen Datums- und Zeitfunktionen benutzt wird.
    • date_diff - Alias von DateTime::diff
    • date_format - Alias von DateTime::format
    • date_get_last_errors - Alias von DateTimeImmutable::getLastErrors
    • date_interval_create_from_date_string - Alias von DateInterval::createFromDateString
    • date_interval_format - Alias von DateInterval::format
    • date_isodate_set - Alias von DateTime::setISODate
    • date_modify - Alias von DateTime::modify
    • date_offset_get - Alias von DateTime::getOffset
    • date_parse - Liefert ein assoziatives Array mit detaillierten Informationen zu einem gegebenen Datum/Zeitpunkt
    • date_parse_from_format - Ermittelt Informationen über das angegebene Datum anhand des angegebenen Formats
    • date_sub - Alias von DateTime::sub
    • date_sunrise - Liefert die Uhrzeit des Sonnenaufgangs für den angegebenen Tag und Ort
    • date_sunset - Liefert die Uhrzeit des Sonnenuntergangs für den angegebenen Tag und Ort
    • date_sun_info - Liefert ein Array mit Informationen über Sonnenauf- und -untergang sowie Beginn und Ende der Dämmerung
    • date_timestamp_get - Alias von DateTime::getTimestamp
    • date_timestamp_set - Alias von DateTime::setTimestamp
    • date_timezone_get - Alias von DateTime::getTimezone
    • date_timezone_set - Alias von DateTime::setTimezone
    • date_time_set - Alias von 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 - Hängt einen Datensatz an eine Datenbank an
    • dbase_close - Schließt eine Datenbank
    • dbase_create - Erzeugt eine Datenbank
    • dbase_delete_record - Markiert einen Datensatz als gelöscht
    • dbase_get_header_info - Liefert Informationen des Dateikopfs einer Datenbank
    • dbase_get_record - Liefert einen Datensatz aus einer Datenbank als indiziertes Array
    • dbase_get_record_with_names - Liefert einen Datensatz aus einer Datenbank als assoziatives Array
    • dbase_numfields - Liefert die Anzahl der Felder einer Datenbank
    • dbase_numrecords - Liefert die Anzahl der Datensätze einer Datenbank
    • dbase_open - Öffnet eine Datenbank
    • dbase_pack - Entfernt die als gelöscht markierten Datensätze aus einer Datenbank
    • dbase_replace_record - Ersetzt einen Datensatz in einer Datenbank
    • dba_close - Schließt eine DBA-Datenbank
    • dba_delete - Löscht den zum angegebenen Schlüssel gehörigen DBA-Eintrag
    • dba_exists - Überprüft, ob ein angegebener Schlüssel existiert
    • dba_fetch - Liest die Daten zu einem angegebenen Schlüssel aus
    • dba_firstkey - Liefert den ersten Schlüssel
    • dba_handlers - Listet alle verfügbaren Handler auf
    • dba_insert - Fügt einen Eintrag ein
    • dba_key_split - Zerlegt einen Schlüssel in Zeichenketten-Darstellung in eine Array-Darstellung
    • dba_list - Listet alle offenen Datenbank-Dateien auf
    • dba_nextkey - Liefert den nachfolgenden Schlüssel
    • dba_open - Öffnet eine Datenbank
    • dba_optimize - Optimiert eine Datenbank
    • dba_popen - Öffnet eine persistente Datenbank-Verbindung
    • dba_replace - Ersetzt einen Eintrag oder fügt ihn ein
    • dba_sync - Synchronisiert eine Datenbank
    • dcgettext - Überschreibt die gesetzte Domain für eine einzelne Abfrage
    • dcngettext - Pluralversion von dcgettext
    • debug_backtrace - Erzeugt eine Ablaufverfolgung
    • debug_print_backtrace - Gibt die Daten für eine Ablaufverfolgung aus
    • debug_zval_dump - Dumps a string representation of an internal zval structure to output
    • decbin - Wandelt von dezimal zu binär um
    • dechex - Wandelt von dezimal zu hexadezimal um
    • decoct - Wandelt von dezimal zu oktal um
    • define - Definiert eine benannte Konstante
    • defined - Prüft, ob eine Konstante mit dem angegebenen Namen existiert
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Rechnet einen Winkel von Grad in Bogenmaß um
    • delete - Siehe unlink oder unset
    • dgettext - Überschreibt die aktuelle Domain
    • die - Entspricht exit
    • dio_close - Schließt eine Datei
    • dio_fcntl - Modifiziert einen Dateideskriptor
    • dio_open - Öffnet eine Datei (falls nötig, wird diese erzeugt) auf einem niedrigeren Level als es die C-Bibliotheks Ein-/Ausgabe-Stream-Funktionen erlauben
    • dio_read - Liest von einem Dateideskriptor
    • dio_seek - Setzt den Dateizeiger
    • dio_stat - Liefert Statusinformationen über einen Dateideskriptor
    • dio_tcsetattr - Setzt Terminalattribute und Baudrate für eine serielle Schnittstelle
    • dio_truncate - Schneidet eine Datei ab
    • dio_write - Schreibt Daten in eine Datei
    • dir - Liefert eine Instanz der Directory-Klasse
    • Directory::close - Schließt das Verzeichnis-Handle
    • Directory::read - Liest einen Eintrag vom Verzeichnis-Handle
    • Directory::rewind - Setzt das Verzeichnis-Handle zurück
    • DirectoryIterator::current - Return the current DirectoryIterator item
    • DirectoryIterator::getBasename - Get base name of current DirectoryIterator item
    • DirectoryIterator::getExtension - Gets the file extension
    • 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 - Seek to a DirectoryIterator item
    • DirectoryIterator::valid - Check whether current DirectoryIterator position is a valid file
    • DirectoryIterator::__construct - Constructs a new directory iterator from a path
    • DirectoryIterator::__toString - Get file name as a string
    • dirname - Liefert den Pfad des übergeordneten Verzeichnisses
    • diskfreespace - Alias von disk_free_space
    • disk_free_space - Liefert den verfügbaren Platz auf einem Dateisystem oder einer Partition
    • disk_total_space - Liefert die Gesamtgröße eines Dateisystemes oder einer Partition
    • dl - Lädt eine PHP-Erweiterung zur Laufzeit
    • dngettext - Pluralversion von dgettext
    • dns_check_record - Alias von checkdnsrr
    • dns_get_mx - Alias von getmxrr
    • dns_get_record - Liefert die zu einem Hostnamen gehörenden DNS-Einträge
    • DocResult::fetchAll - Ruft alle Zeilen aus einer Ergebnismenge ab
    • DocResult::fetchOne - Ruft eine Zeile aus einer Ergebnismenge ab
    • DocResult::getWarnings - Ruft die Warnungen der letzten Operation ab
    • DocResult::getWarningsCount - Ermittelt die Anzahl der Warnungen der letzten Operation
    • DocResult::__construct - Der Konstruktor der Klasse DocResult
    • 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 - Adds new child at the end of the children
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DOMNode::cloneNode - Clones a node
    • DOMNode::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 - Breaks this node into two nodes at the specified offset
    • DOMText::__construct - Creates a new DOMText object
    • DOMXPath::evaluate - Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query - Evaluates the given XPath expression
    • DOMXPath::registerNamespace - Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions - Register PHP functions as XPath functions
    • DOMXPath::__construct - Creates a new DOMXPath object
    • dom_import_simplexml - Ermittelt ein DOMElement-Objekt aus einem SimpleXMLElement-Objekt
    • dotnet::__construct - dotnet class constructor
    • doubleval - Alias von floatval
    • Ds\Collection::clear - Removes all values
    • Ds\Collection::copy - Returns a shallow copy of the collection
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an Array
    • Ds\Deque::allocate - Allocates enough memory for a required capacity
    • Ds\Deque::apply - Updates all values by applying a callback function to each value
    • Ds\Deque::capacity - Returns the current capacity
    • Ds\Deque::clear - Removes all values from the deque
    • Ds\Deque::contains - Determines if the deque contains given values
    • Ds\Deque::copy - Returns a shallow copy of the deque
    • Ds\Deque::count - Returns the number of values in the collection
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find - Attempts to find a value's index
    • Ds\Deque::first - Returns the first value in the deque
    • Ds\Deque::get - Returns the value at a given index
    • Ds\Deque::insert - Inserts values at a given index
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Deque::last - Returns the last value
    • Ds\Deque::map - Returns the result of applying a callback to each value
    • Ds\Deque::merge - Returns the result of adding all given values to the deque
    • Ds\Deque::pop - Removes and returns the last value
    • Ds\Deque::push - Adds values to the end of the deque
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function
    • Ds\Deque::remove - Removes and returns a value by index
    • Ds\Deque::reverse - Reverses the deque in-place
    • Ds\Deque::reversed - Returns a reversed copy
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations
    • Ds\Deque::set - Updates a value at a given index
    • Ds\Deque::shift - Removes and returns the first value
    • Ds\Deque::slice - Returns a sub-deque of a given range
    • Ds\Deque::sort - Sorts the deque in-place
    • Ds\Deque::sorted - Returns a sorted copy
    • Ds\Deque::sum - Returns the sum of all values in the deque
    • Ds\Deque::toArray - Converts the deque to an Array
    • Ds\Deque::unshift - Adds values to the front of the deque
    • Ds\Deque::__construct - Creates a new instance
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value
    • Ds\Map::allocate - Allocates enough memory for a required capacity
    • Ds\Map::apply - Updates all values by applying a callback function to each value
    • Ds\Map::capacity - Returns the current capacity
    • Ds\Map::clear - Removes all values
    • Ds\Map::copy - Returns a shallow copy of the map
    • Ds\Map::count - Returns the number of values in the map
    • Ds\Map::diff - Creates a new map using keys that aren't in another map
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first - Returns the first pair in the map
    • Ds\Map::get - Returns the value for a given key
    • Ds\Map::hasKey - Determines whether the map contains a given key
    • Ds\Map::hasValue - Determines whether the map contains a given value
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Map::keys - Returns a set of the map's keys
    • Ds\Map::ksort - Sorts the map in-place by key
    • Ds\Map::ksorted - Returns a copy, sorted by key
    • Ds\Map::last - Returns the last pair of the map
    • Ds\Map::map - Returns the result of applying a callback to each value
    • Ds\Map::merge - Returns the result of adding all given associations
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map
    • Ds\Map::put - Associates a key with a value
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce - Reduces the map to a single value using a callback function
    • Ds\Map::remove - Removes and returns a value by key
    • Ds\Map::reverse - Reverses the map in-place
    • Ds\Map::reversed - Returns a reversed copy
    • Ds\Map::skip - Returns the pair at a given positional index
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort - Sorts the map in-place by value
    • Ds\Map::sorted - Returns a copy, sorted by value
    • Ds\Map::sum - Returns the sum of all values in the map
    • Ds\Map::toArray - Converts the map to an Array
    • Ds\Map::union - Creates a new map using values from the current instance and another map
    • Ds\Map::values - Returns a sequence of the map's values
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both
    • Ds\Map::__construct - Creates a new instance
    • Ds\Pair::clear - Removes all values
    • Ds\Pair::copy - Returns a shallow copy of the pair
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Pair::toArray - Converts the pair to an Array
    • Ds\Pair::__construct - Creates a new instance
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity - Returns the current capacity
    • Ds\PriorityQueue::clear - Removes all values
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue
    • Ds\PriorityQueue::count - Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push - Pushes values into the queue
    • Ds\PriorityQueue::toArray - Converts the queue to an Array
    • Ds\PriorityQueue::__construct - Creates a new instance
    • Ds\Queue::allocate - Allocates enough memory for a required capacity
    • Ds\Queue::capacity - Returns the current capacity
    • Ds\Queue::clear - Removes all values
    • Ds\Queue::copy - Returns a shallow copy of the queue
    • Ds\Queue::count - Returns the number of values in the queue
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Queue::peek - Returns the value at the front of the queue
    • Ds\Queue::pop - Removes and returns the value at the front of the queue
    • Ds\Queue::push - Pushes values into the queue
    • Ds\Queue::toArray - Converts the queue to an Array
    • Ds\Queue::__construct - Creates a new instance
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity - Returns the current capacity
    • Ds\Sequence::contains - Determines if the sequence contains given values
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find - Attempts to find a value's index
    • Ds\Sequence::first - Returns the first value in the sequence
    • Ds\Sequence::get - Returns the value at a given index
    • Ds\Sequence::insert - Inserts values at a given index
    • Ds\Sequence::join - Joins all values together as a string
    • Ds\Sequence::last - Returns the last value
    • Ds\Sequence::map - Returns the result of applying a callback to each value
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop - Removes and returns the last value
    • Ds\Sequence::push - Adds values to the end of the sequence
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove - Removes and returns a value by index
    • Ds\Sequence::reverse - Reverses the sequence in-place
    • Ds\Sequence::reversed - Returns a reversed copy
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations
    • Ds\Sequence::set - Updates a value at a given index
    • Ds\Sequence::shift - Removes and returns the first value
    • Ds\Sequence::slice - Returns a sub-sequence of a given range
    • Ds\Sequence::sort - Sorts the sequence in-place
    • Ds\Sequence::sorted - Returns a sorted copy
    • Ds\Sequence::sum - Returns the sum of all values in the sequence
    • Ds\Sequence::unshift - Adds values to the front of the sequence
    • Ds\Set::add - Adds values to the set
    • Ds\Set::allocate - Allocates enough memory for a required capacity
    • Ds\Set::capacity - Returns the current capacity
    • Ds\Set::clear - Removes all values
    • Ds\Set::contains - Determines if the set contains all values
    • Ds\Set::copy - Returns a shallow copy of the set
    • Ds\Set::count - Returns the number of values in the set
    • Ds\Set::diff - Creates a new set using values that aren't in another set
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include
    • Ds\Set::first - Returns the first value in the set
    • Ds\Set::get - Returns the value at a given index
    • Ds\Set::intersect - Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Set::last - Returns the last value in the set
    • Ds\Set::merge - Returns the result of adding all given values to the set
    • Ds\Set::reduce - Reduces the set to a single value using a callback function
    • Ds\Set::remove - Removes all given values from the set
    • Ds\Set::reverse - Reverses the set in-place
    • Ds\Set::reversed - Returns a reversed copy
    • Ds\Set::slice - Returns a sub-set of a given range
    • Ds\Set::sort - Sorts the set in-place
    • Ds\Set::sorted - Returns a sorted copy
    • Ds\Set::sum - Returns the sum of all values in the set
    • Ds\Set::toArray - Converts the set to an Array
    • Ds\Set::union - Creates a new set using values from the current instance and another set
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both
    • Ds\Set::__construct - Creates a new instance
    • Ds\Stack::allocate - Allocates enough memory for a required capacity
    • Ds\Stack::capacity - Returns the current capacity
    • Ds\Stack::clear - Removes all values
    • Ds\Stack::copy - Returns a shallow copy of the stack
    • Ds\Stack::count - Returns the number of values in the stack
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Stack::peek - Returns the value at the top of the stack
    • Ds\Stack::pop - Removes and returns the value at the top of the stack
    • Ds\Stack::push - Pushes values onto the stack
    • Ds\Stack::toArray - Converts the stack to an Array
    • Ds\Stack::__construct - Creates a new instance
    • Ds\Vector::allocate - Allocates enough memory for a required capacity
    • Ds\Vector::apply - Updates all values by applying a callback function to each value
    • Ds\Vector::capacity - Returns the current capacity
    • Ds\Vector::clear - Removes all values
    • Ds\Vector::contains - Determines if the vector contains given values
    • Ds\Vector::copy - Returns a shallow copy of the vector
    • Ds\Vector::count - Returns the number of values in the collection
    • Ds\Vector::filter - Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find - Attempts to find a value's index
    • Ds\Vector::first - Returns the first value in the vector
    • Ds\Vector::get - Returns the value at a given index
    • Ds\Vector::insert - Inserts values at a given index
    • Ds\Vector::isEmpty - Returns whether the vector is empty
    • Ds\Vector::join - Joins all values together as a string
    • Ds\Vector::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Vector::last - Returns the last value
    • Ds\Vector::map - Returns the result of applying a callback to each value
    • Ds\Vector::merge - Returns the result of adding all given values to the vector
    • Ds\Vector::pop - Removes and returns the last value
    • Ds\Vector::push - Adds values to the end of the vector
    • Ds\Vector::reduce - Reduces the vector to a single value using a callback function
    • Ds\Vector::remove - Removes and returns a value by index
    • Ds\Vector::reverse - Reverses the vector in-place
    • Ds\Vector::reversed - Returns a reversed copy
    • Ds\Vector::rotate - Rotates the vector by a given number of rotations
    • Ds\Vector::set - Updates a value at a given index
    • Ds\Vector::shift - Removes and returns the first value
    • Ds\Vector::slice - Returns a sub-vector of a given range
    • Ds\Vector::sort - Sorts the vector in-place
    • Ds\Vector::sorted - Returns a sorted copy
    • Ds\Vector::sum - Returns the sum of all values in the vector
    • Ds\Vector::toArray - Converts the vector to an Array
    • Ds\Vector::unshift - Adds values to the front of the vector
    • Ds\Vector::__construct - Creates a new instance
  • e
    • each - Liefert das aktuelle Schlüssel-Wert-Paar eines Arrays und rückt den Arrayzeiger vor
    • easter_date - Zeitpunkt des Osterfestes (0 Uhr) als Unix-Timestamp
    • easter_days - Anzahl der Tage zwischen dem 21. März und Ostersonntag
    • echo - Gibt einen oder mehrere Strings aus
    • 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 - Prüft, ob eine Variable leer ist
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - Checks whether the current element is valid
    • 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 - Alias von 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 - Alias von 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 - Positioniert den internen Zeiger eines Arrays auf dessen letztes Element
    • enum_exists - Prüft, ob eine Aufzählung definiert ist
    • Error::getCode - Gibt den Fehlercode zurück
    • Error::getFile - Gibt die Datei zurück in der der Fehler
    • Error::getLine - Gibt die Zeile zurück in der der Fehler auftrat
    • Error::getMessage - Gibt die Fehlermeldung zurück
    • Error::getPrevious - Gibt das vorherige Throwable zurück
    • Error::getTrace - Gibt den Stacktrace zurück
    • Error::getTraceAsString - Gibt den Stacktrace als String zurück
    • Error::__clone - Klont einen Fehler
    • Error::__construct - Erzeugt ein Error-Objekt
    • Error::__toString - Gibt eine Repräsentation des Fehlers als String zurück
    • ErrorException::getSeverity - Liefert die Schwere der Exception
    • ErrorException::__construct - Erstellt die Exception
    • error_clear_last - Clear the most recent error
    • error_get_last - Liefert den zuletzt aufgetretenen Fehler
    • error_log - Sendet eine Fehlermeldung an die definierten Fehlerbehandlungsroutinen
    • error_reporting - Gibt an, welche PHP-Fehlermeldungen gemeldet werden
    • escapeshellarg - Maskiert eine Zeichenkette (String), um sie als Shell-Argument benutzen zu können
    • escapeshellcmd - Maskiert Metazeichen der 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 - Wertet eine Zeichenkette als PHP-Code aus
    • 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 - Alias von Event::add
    • Event::addTimer - Alias von Event::add
    • Event::del - Makes event non-pending
    • Event::delSignal - Alias von Event::del
    • Event::delTimer - Alias von 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 - Beschreibung
    • 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 - Schreibt den Inhalt des Puffers in eine Datei oder ein 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 - Fügt Daten zum Ausgabepuffer eines Pufferereignises hinzu
    • 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 - Gibt die Fehlernummer der Exception zurück
    • Exception::getFile - Gibt den Namen der Datei zurück, in der die Exception erzeugt wurde
    • Exception::getLine - Gibt die Zeile zurück, in der die Exception erzeugt wurde
    • Exception::getMessage - Gibt die Exceptionbeschreibung zurück
    • Exception::getPrevious - Gibt die vorhergehende Throwable zurück
    • Exception::getTrace - Gibt den Stacktrace zurück
    • Exception::getTraceAsString - Gibt den Stacktrace als String zurück
    • Exception::__clone - Klont die Exception
    • Exception::__construct - Erstellt die Exception
    • Exception::__toString - Stringrepräsentation der Exception
    • exec - Führt ein externes Programm aus
    • Executable::execute - Führt eine Anweisung aus
    • ExecutionStatus::__construct - Der Konstruktor der Klasse ExecutionStatus
    • exif_imagetype - Ermittelt den Bildtyp
    • exif_read_data - Liest die EXIF-Header einer Bilddatei aus
    • exif_tagname - Gibt den Header-Namen für einen Index zurück
    • exif_thumbnail - Liest das eingebettete Miniaturbild eines Bildes aus
    • exit - Gibt eine Meldung aus und beendet das aktuelle Skript
    • exp - Berechnet den Exponenten von e
    • expect:// - Process Interaction Streams
    • 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 - Teilt eine Zeichenkette anhand einer Zeichenkette
    • expm1 - Berechnet exp(Zahl) - 1 mit guter Genauigkeit, auch wenn Zahl nahe bei Null liegt
    • expression - Bindet die Variablen der vorbereiteten Anweisung als Parameter
    • Expression::__construct - Der Konstruktor der Klasse Expression
    • extension_loaded - Prüft, ob eine Erweiterung geladen ist
    • extract - Importiert Variablen eines Arrays in die aktuelle Symboltabelle
    • ezmlm_hash - Berechnet den Hash-Wert, der von EZMLM benötigt wird
  • 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 - Flushes all response data to the client
    • fbird_add_user - Alias von ibase_add_user
    • fbird_affected_rows - Alias von ibase_affected_rows
    • fbird_backup - Alias von ibase_backup
    • fbird_blob_add - Alias von ibase_blob_add
    • fbird_blob_cancel - Cancel creating blob
    • fbird_blob_close - Alias von ibase_blob_close
    • fbird_blob_create - Alias von ibase_blob_create
    • fbird_blob_echo - Alias von ibase_blob_echo
    • fbird_blob_get - Alias von ibase_blob_get
    • fbird_blob_import - Alias von ibase_blob_import
    • fbird_blob_info - Alias von ibase_blob_info
    • fbird_blob_open - Alias von ibase_blob_open
    • fbird_close - Alias von ibase_close
    • fbird_commit - Alias von ibase_commit
    • fbird_commit_ret - Alias von ibase_commit_ret
    • fbird_connect - Alias von ibase_connect
    • fbird_db_info - Alias von ibase_db_info
    • fbird_delete_user - Alias von ibase_delete_user
    • fbird_drop_db - Alias von ibase_drop_db
    • fbird_errcode - Alias von ibase_errcode
    • fbird_errmsg - Alias von ibase_errmsg
    • fbird_execute - Alias von ibase_execute
    • fbird_fetch_assoc - Alias von ibase_fetch_assoc
    • fbird_fetch_object - Alias von ibase_fetch_object
    • fbird_fetch_row - Alias von ibase_fetch_row
    • fbird_field_info - Alias von ibase_field_info
    • fbird_free_event_handler - Alias von ibase_free_event_handler
    • fbird_free_query - Alias von ibase_free_query
    • fbird_free_result - Alias von ibase_free_result
    • fbird_gen_id - Alias von ibase_gen_id
    • fbird_maintain_db - Alias von ibase_maintain_db
    • fbird_modify_user - Alias von ibase_modify_user
    • fbird_name_result - Alias von ibase_name_result
    • fbird_num_fields - Alias von ibase_num_fields
    • fbird_num_params - Alias von ibase_num_params
    • fbird_param_info - Alias von ibase_param_info
    • fbird_pconnect - Alias von ibase_pconnect
    • fbird_prepare - Alias von ibase_prepare
    • fbird_query - Alias von ibase_query
    • fbird_restore - Alias von ibase_restore
    • fbird_rollback - Alias von ibase_rollback
    • fbird_rollback_ret - Alias von ibase_rollback_ret
    • fbird_server_info - Alias von ibase_server_info
    • fbird_service_attach - Alias von ibase_service_attach
    • fbird_service_detach - Alias von ibase_service_detach
    • fbird_set_event_handler - Alias von ibase_set_event_handler
    • fbird_trans - Alias von ibase_trans
    • fbird_wait_event - Alias von ibase_wait_event
    • fclose - Schließt einen offenen Dateizeiger
    • fdatasync - Synchronizes data (but not meta-data) to the file
    • fdf_add_doc_javascript - Fügt JavaScript-Code in ein FDF-Dokument ein
    • fdf_add_template - Fügt dem FDF Dokument ein Template hinzu
    • fdf_close - Schließt ein FDF Dokument
    • fdf_create - Erzeugt ein neues FDF Dokument
    • fdf_enum_values - Ruft für jeden Dokumentwert eine benutzerdefinierte Funktion auf
    • fdf_errno - Gibt den Fehlercode der letzten FDF Operation zurück
    • fdf_error - Gibt die Beschrebung eines Fehlercodes zurück
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Liefert den Wert des /Encoding Schlüssels
    • fdf_get_file - Gibt den Wert des /F Schlüssels zurück
    • fdf_get_flags - Ermittelt die Flags eines Feldes
    • fdf_get_opt - Liefert einen Wert aus dem Optionsarray eines Feldes
    • fdf_get_status - Gibt den Wert des /STATUS Schlüssels zurück
    • fdf_get_value - Gibt den Wert eines Feldes zurück
    • fdf_get_version - Liefert die Versionsnummer einer FDF Datei oder des APIs
    • fdf_header - Setzt FDF-spezifische Header
    • fdf_next_field_name - Gibt den Namen des nächsten Feldes zurück
    • fdf_open - Öffnet ein FDF Dokument
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Speichern eines FDF Dokuments
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Legt das Aussehen eines Feldes fest
    • fdf_set_encoding - Legt die FDF Zeichenkodierung fest
    • fdf_set_file - Definiert ein PDF-Dokument, das FDF-Daten anzeigen soll
    • fdf_set_flags - Setzt Flags eines Feldes
    • fdf_set_javascript_action - Weist einem Feld eine JavaScript Aktion zu
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Legt eine Option eines Feldes fest
    • fdf_set_status - Setzt den Wert des /STATUS Schlüssels
    • fdf_set_submit_form_action - Setzt eine Submit-Form-Aktion für ein Feld
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Legt den Wert eines Feldes fest
    • fdf_set_version - Sets version number for a FDF file
    • fdiv - Dividiert zwei Zahlen gemäß IEEE 754
    • feof - Prüft, ob ein Dateizeiger am Ende der Datei steht
    • 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 - Schreibt den Ausgabepuffer in eine Datei
    • fgetc - Liest das Zeichen, auf welches der Dateizeiger zeigt
    • fgetcsv - Liest eine Zeile von der Position des Dateizeigers und prüft diese auf kommaseparierte Werte (CSV)
    • fgets - Liest die Zeile von der Position des Dateizeigers
    • fgetss - Liest eine Zeile von der Position des Dateizeigers und entfernt HTML Tags.
    • Fiber::getCurrent - Ermittelt die aktuell laufende Instanz von Fiber
    • Fiber::getReturn - Ermittelt den von einer Fiber zurückgegebenen Wert
    • Fiber::isRunning - Prüft, ob gerade eine Fiber aktiv ist
    • Fiber::isStarted - Prüft, ob eine Fiber gestartet wurde
    • Fiber::isSuspended - Prüft, ob eine Fiber unterbrochen wurde
    • Fiber::isTerminated - Prüft, ob eine Fiber beendet wurde
    • Fiber::resume - Setzt die Ausführung einer Fiber mit einem Wert fort
    • Fiber::start - Startet die Ausführung einer Fiber
    • Fiber::suspend - Unterbricht die Ausführung der aktuellen Fiber
    • Fiber::throw - Setzt die Ausführung einer Fiber mit einer Exception fort
    • Fiber::__construct - Erstellt eine neue Instanz von Fiber
    • FiberError::__construct - Konstruktor, um die direkte Instanziierung zu unterbinden
    • file - Liest eine komplette Datei in ein Array
    • file:// - Accessing local filesystem
    • fileatime - Liefert die Zeit des letzten Zugriffs auf eine Datei
    • filectime - Liefert die Änderungszeit eines Datei-Inodes
    • filegroup - Liefert die Gruppenzugehörigkeit einer Datei
    • fileinode - Liefert die Inode-Nummer einer Datei
    • filemtime - Liefert die Zeit der letzten Dateiänderung
    • fileowner - Liefert den Eigentümer einer Datei
    • fileperms - Liefert die Zugriffsrechte einer Datei
    • filesize - Liefert die Größe einer Datei
    • 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 - Liefert den Typ einer Datei
    • file_exists - Prüft, ob eine Datei oder ein Verzeichnis existiert
    • file_get_contents - Liest die gesamte Datei in einen String
    • file_put_contents - Schreibt Daten in eine Datei
    • FilterIterator::accept - Check whether the current element of the iterator is acceptable
    • FilterIterator::current - Get the current element value
    • FilterIterator::key - Get the current key
    • FilterIterator::next - Move the iterator forward
    • FilterIterator::rewind - Rewind the iterator
    • FilterIterator::valid - Check whether the current element is valid
    • FilterIterator::__construct - Construct a filterIterator
    • filter_has_var - Prüft, ob eine Variable des angegebenen Typs existiert
    • filter_id - Liefert die Filter-ID zu einem Filternamen
    • filter_input - Nimmt eine Variable von Außen entgegen und filtert sie optional
    • filter_input_array - Nimmt mehrere Variablen von Außen entgegen und filtert sie optional
    • filter_list - Liefert eine Liste aller unterstützten Filter
    • filter_var - Filtert eine Variable mit einem angegebenen Filter
    • filter_var_array - Nimmt mehrere Variablen entgegen und filtert sie optional
    • finfo::buffer - Alias von finfo_buffer()
    • finfo::file - Alias von finfo_file()
    • finfo::set_flags - Alias von finfo_set_flags()
    • finfo::__construct - Alias von finfo_open
    • finfo_close - Schließt eine Fileinfo-Instanz
    • finfo_open - Erstellt eine neue Fileinfo-Instanz
    • floatval - Konvertiert einen Wert nach float
    • flock - Portables Datei-Sperrverfahren (advisory locking)
    • floor - Rundet Brüche ab
    • flush - Leert (sendet) den System-Ausgabepuffer
    • fmod - Rest einer Gleitkommadivision (Modulus)
    • fnmatch - Match filename against a pattern
    • fopen - Öffnet eine Datei oder URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Gibt alle verbleibenden Daten eines Dateizeigers aus
    • fpm_get_status - Returns the current FPM pool status
    • fprintf - Schreibt einen formatierten String in einen Stream
    • fputcsv - Format line as CSV and write to file pointer
    • fputs - Alias von fwrite
    • fread - Liest Binärdaten aus einer Datei
    • frenchtojd - Konvertiert ein Datum des Französischen Revolutionskalenders zu einer julianischen Tageszahl
    • fscanf - Interpretiert den Input einer Datei entsprechend einem angegebenen Format
    • fseek - Positioniert den Dateizeiger
    • fsockopen - Stellt eine Internet- oder Unix-Domain-Socket-Verbindung her
    • fstat - Sammelt Informationen über eine Datei mittels eines offenen Dateizeigers
    • fsync - Synchronizes changes to the file (including meta-data)
    • ftell - Ermittelt die aktuelle Position des Dateizeigers
    • ftok - Erzeugt aus einem Dateipfad und einem Projektbezeichner einen System-V-IPC-Schlüssel
    • FTP-Kontextoptionen - Liste der FTP-Kontextoptionen
    • ftp:// - Accessing FTP(s) URLs
    • ftp_alloc - Reserviert Platz für eine hochzuladende Datei
    • ftp_append - Hängt den Inhalt einer Datei an eine andere Datei auf dem FTP-Server
    • ftp_cdup - Wechselt in das darüberliegende Verzeichnis
    • ftp_chdir - Wechselt das Verzeichnis auf einem FTP-Server
    • ftp_chmod - Ändert die Zugriffsrechte einer Datei über FTP
    • ftp_close - Schließt eine FTP-Verbindung
    • ftp_connect - Stellt eine FTP-Verbindung her
    • ftp_delete - Löscht eine Datei auf dem FTP-Server
    • ftp_exec - Fordert die Ausführung eines Programmes auf dem FTP-Server an
    • ftp_fget - Lädt eine Datei vom FTP-Server und speichert sie in eine geöffnete Datei
    • ftp_fput - Überträgt eine geöffnete Datei auf einen FTP-Server
    • ftp_get - Lädt eine Datei von einem FTP-Server herunter
    • ftp_get_option - Ruft diverse Laufzeitoptionen der angegebenen FTP-Verbindung ab
    • ftp_login - Loggt sich bei einer FTP-Verbindung ein
    • ftp_mdtm - Liefert den Zeitpunkt der letzten Änderung der angegebenen Datei
    • ftp_mkdir - Erzeugt ein Verzeichnis
    • ftp_mlsd - Liefert eine Liste der Dateien im angegebenen Verzeichnis
    • ftp_nb_continue - Nimmt die Übertragung einer Datei wieder auf (nicht-blockierend)
    • ftp_nb_fget - Ruft eine Datei vom FTP-Server ab und schreibt sie in eine lokale Datei (nicht-blockierend)
    • ftp_nb_fput - Lädt eine geöffnete Datei auf den FTP-Server (nicht blockierend)
    • ftp_nb_get - Überträgt eine Datei vom FTP-Server und speichert sie lokal (nicht blockierend)
    • ftp_nb_put - Lädt eine Datei auf den FTP-Server (nicht-blockierend)
    • ftp_nlist - Liefert eine Liste der im angegebenen Verzeichnis enthaltenen Dateien
    • ftp_pasv - Schaltet den passiven Modus ein oder aus
    • ftp_put - Lädt eine Datei auf einen FTP-Server
    • ftp_pwd - Liefert den aktuellen Verzeichnisnamen
    • ftp_quit - Alias von ftp_close
    • ftp_raw - Sendet ein beliebiges Kommando an den FTP-Server
    • ftp_rawlist - Liefert eine detaillierte Liste der Dateien im angegebenen Verzeichnis
    • ftp_rename - Benennt eine Datei auf dem FTP-Server um
    • ftp_rmdir - Löscht ein Verzeichnis
    • ftp_set_option - Setzt diverse FTP-Laufzeitoptionen
    • ftp_site - Sendet ein SITE-Kommando zum Server
    • ftp_size - Liefert die Größe der angegebenen Datei
    • ftp_ssl_connect - Öffnet eine sichere SSL-FTP-Verbindung
    • ftp_systype - Liefert den Systemtyp des entfernten FTP-Servers
    • ftruncate - Kürzt eine Datei auf die angegebene Länge
    • function_exists - Falls die angegebene Funktion definiert ist, wird true zurück gegeben
    • func_get_arg - Liefert ein bestimmtes Funktionsargument
    • func_get_args - Liefert Funktionsargumente als Array
    • func_num_args - Liefert die Anzahl der an eine Funktion übergebenen Argumente
    • fwrite - Binär-sicheres Dateischreiben
  • 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 - Liefert Informationen über die aktuell verwendete GD-Bibliothek
    • 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 - Ermittelt den aktuellen Wert eines Generators
    • Generator::getReturn - Ermittelt den Rückgabewert eines Generators
    • Generator::key - Ruft einen gelieferten Schlüssel ab
    • Generator::next - Setzt die Ausführung eines Generators fort
    • Generator::rewind - Setzt den Iterator zurück
    • Generator::send - Sendet einen Wert an einen Generator
    • Generator::throw - Wirft eine Exception in einen Generator
    • Generator::valid - Prüft, ob der Iterator geschlossen wurde
    • Generator::__wakeup - Serialisierungs-Callback
    • geoip_asnum_by_name - Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name - Get the two letter continent code
    • geoip_country_code3_by_name - Get the three letter country code
    • geoip_country_code_by_name - Get the two letter country code
    • geoip_country_name_by_name - Get the full country name
    • geoip_database_info - Get GeoIP Database information
    • geoip_db_avail - Determine if GeoIP Database is available
    • geoip_db_filename - Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info - Returns detailed information about all GeoIP database types
    • geoip_domain_by_name - Get the second level domain name
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name - Get the Internet connection speed
    • geoip_org_by_name - Get the organization name
    • geoip_record_by_name - Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name - Get the country code and region
    • geoip_region_name_by_code - Returns the region name for some country and region code combo
    • geoip_setup_custom_directory - Set a custom directory for the GeoIP database
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • getallheaders - Liefert alle HTTP-Request-Header
    • getcwd - Ermittelt das aktuelle Arbeitsverzeichnis
    • getdate - Liefert Datums- und Zeitinformationen
    • getenv - Liefert den Wert einer einzelnen oder aller Umgebungsvariablen
    • gethostbyaddr - Liefert den zur angegebenen IP-Adresse passenden Internet-Hostnamen
    • gethostbyname - Ermittelt die zum angegebenen Internet-Hostnamen passende IPv4-Adresse
    • gethostbynamel - Liefert eine Liste von IPv4-Adressen passend zum angegebenen Internet-Hostnamen
    • gethostname - Gets the host name
    • getimagesize - Liefert die Größe einer Grafik
    • getimagesizefromstring - Liefert die Größe einer Grafik aus einer Zeichenkette
    • getlastmod - Liefert die Uhrzeit der letzten Änderung eines Skripts
    • getmxrr - Ermittelt die zu einem Internet-Hostnamen passenden MX-Records
    • getmygid - Get PHP script owner's GID
    • getmyinode - Liefert den Inode des aktuellen Skripts
    • getmypid - Liefert die Prozess-ID eines Skripts
    • getmyuid - Liefert die User-ID des Besitzers eines PHP-Skripts
    • getopt - Gets options from the command line argument list
    • getprotobyname - Liefert die Protokollnummer anhand des Protokollnamens
    • getprotobynumber - Liefert den Protokollnamen anhand der Protokollnummer
    • getrandmax - Liefert die größtmögliche Zufallszahl
    • getrusage - Liefert den aktuellen Wert der Ressourcenauslastung
    • getservbyname - Liefert die Portnummer passend zu einem Internet-Dienst und -Protokoll
    • getservbyport - Liefert den Internet-Dienst passend zu einem Port und Protokoll
    • getSession - Baut eine Verbindung zu einem MySQL-Server auf
    • gettext - Sucht eine Meldung in der aktuellen Domain
    • gettimeofday - Ermittelt die aktuelle Zeit
    • gettype - Liefert den Datentyp einer Variablen
    • get_browser - Ermittelt die Fähigkeiten des Browsers eines Benutzers
    • get_called_class - Ermittelt den Namen der von einer statischen Methode aufgerufenen Klasse ("Late Static Binding")
    • get_cfg_var - Liefert den Wert einer Konfigurationsoption
    • get_class - Ermittelt den Klassennamen eines Objekts
    • get_class_methods - Ermittelt die Namen der definierten Methoden einer Klasse
    • get_class_vars - Liefert die Vorgabeeigenschaften einer Klasse
    • get_current_user - Liefert den Benutzernamen des Besitzers des aktuellen PHP-Skripts
    • get_debug_type - Gets the type name of a variable in a way that is suitable for debugging
    • get_declared_classes - Ermittelt die Namen der definierten Klassen
    • get_declared_interfaces - Gibt ein Array mit allen definierten Interfaces zurück
    • get_declared_traits - Liefert ein Array mit allen deklarierten Traits
    • get_defined_constants - Returns an associative array with the names of all the constants and their values
    • get_defined_functions - Liefert ein Array aller definierten Funktionen
    • get_defined_vars - Gibt ein Array aller definierten Variablen zurück
    • get_extension_funcs - Liefert die Namen der Funktionen einer Erweiterung
    • get_headers - Ruft alle Header ab, die der Server als Antwort auf einen HTTP-Request versendet
    • get_html_translation_table - Liefert die Umwandlungstabelle, die von htmlspecialchars und htmlentities verwendet wird
    • get_included_files - Liefert ein Array mit den Namen der eingebundenen Dateien
    • get_include_path - Gets the current include_path configuration option
    • get_loaded_extensions - Liefert ein Array mit den Namen aller einkompilierten und geladenen Erweiterungen
    • get_magic_quotes_gpc - Liefert die aktuelle Konfiguration von magic_quotes_gpc
    • get_magic_quotes_runtime - Liefert die aktuelle Konfiguration von magic_quotes_runtime
    • get_mangled_object_vars - Liefert ein Array mit aufbereiteten Objekteigenschaften
    • get_meta_tags - Liest alle content-Attribute der Meta-Tags einer Datei aus und gibt ein Array zurück
    • get_object_vars - Liefert die Eigenschaften eines Objekts
    • get_parent_class - Gibt den Namen der Elternklasse eines Objektes zurück
    • get_required_files - Alias von get_included_files
    • get_resources - Returns active resources
    • get_resource_id - Returns an integer identifier for the given resource
    • get_resource_type - Liefert den Typ einer Ressource
    • glob - Findet Dateinamen, die mit einem Muster übereinstimmen
    • glob:// - Find pathnames matching pattern
    • 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 - Alias von 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 - Gibt die Farbe zurück
    • 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 - Erstellt ein neues GmagickPixel-Objekt
    • gmdate - Formatiert eine GMT/UTC Zeit-/Datumsangabe
    • gmmktime - Liefert den Unix-Zeitstempel für ein GMT-Datum
    • GMP::__construct - Create GMP number
    • GMP::__serialize - Serializes the GMP object
    • GMP::__unserialize - Deserializes the data parameter into a GMP object
    • gmp_abs - Absolute value
    • gmp_add - Add numbers
    • gmp_and - Bitwise AND
    • gmp_binomial - Calculates binomial coefficient
    • gmp_clrbit - Clear bit
    • gmp_cmp - Compare numbers
    • gmp_com - Calculates one's complement
    • gmp_div - Alias von gmp_div_q
    • gmp_divexact - Exact division of numbers
    • gmp_div_q - Divide numbers
    • gmp_div_qr - Divide numbers and get quotient and remainder
    • gmp_div_r - Remainder of the division of numbers
    • gmp_export - Export to a binary string
    • gmp_fact - Factorial
    • gmp_gcd - Calculate GCD
    • gmp_gcdext - Calculate GCD and multipliers
    • gmp_hamdist - Hamming distance
    • gmp_import - Import from a binary string
    • gmp_init - Create GMP number
    • gmp_intval - Convert GMP number to integer
    • gmp_invert - Inverse by modulo
    • gmp_jacobi - Jacobi symbol
    • gmp_kronecker - Kronecker symbol
    • gmp_lcm - Calculate LCM
    • gmp_legendre - Legendre symbol
    • gmp_mod - Modulo operation
    • gmp_mul - Multiply numbers
    • gmp_neg - Negate number
    • gmp_nextprime - Find next prime number
    • gmp_or - Bitwise OR
    • gmp_perfect_power - Perfect power check
    • gmp_perfect_square - Perfect square check
    • gmp_popcount - Population count
    • gmp_pow - Raise number into power
    • gmp_powm - Raise number into power with modulo
    • gmp_prob_prime - Check if number is "probably prime"
    • gmp_random - Random number
    • gmp_random_bits - Random number
    • gmp_random_range - 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 - Sign of number
    • gmp_sqrt - Calculate square root
    • gmp_sqrtrem - Square root with remainder
    • gmp_strval - Convert GMP number to string
    • gmp_sub - Subtract numbers
    • gmp_testbit - Tests if a bit is set
    • gmp_xor - Bitwise XOR
    • gmstrftime - Formatiert eine Datums-/Zeitangabe in GMT/UTC-Format entsprechend den Locale-Einstellungen
    • gnupg_adddecryptkey - Fügt einen Schlüssel für Entschlüsselung hinzu
    • gnupg_addencryptkey - Fügt einen Schlüssel zur Verschlüsselung hinzu
    • gnupg_addsignkey - Fügt einen Schlüssel für Signierung hinzu
    • gnupg_cleardecryptkeys - Entfernt alle Schlüssel, die vorher für Entschlüsselung hinterlegt wurden
    • gnupg_clearencryptkeys - Entfernt alle Schlüssel, die vorher zur Verschlüsselung hinterlegt wurden
    • gnupg_clearsignkeys - Entfernt alle Schlüssel die vorher zur Signierung hinterlegt wurden
    • gnupg_decrypt - Entschlüsselt einen gegebenen Text
    • gnupg_decryptverify - Entschlüsselt und vertifiziert einen gegebenen Text
    • gnupg_deletekey - Löscht einen Schlüssel aus dem Schlüsselbund
    • gnupg_encrypt - Verschlüsselt einen gegebenen Text
    • gnupg_encryptsign - Verschlüsselt und signiert einen gegebenen Text
    • gnupg_export - Exportiert einen Schlüssel
    • gnupg_getengineinfo - Liefert Informationen über die Engine
    • gnupg_geterror - Gibt den Fehlertext zurück, wenn eine Funktion scheitert
    • gnupg_geterrorinfo - Liefert Fehlerinformationen
    • gnupg_getprotocol - Gibt das aktuell für alle Operationen aktive Protokoll zurück
    • gnupg_gettrustlist - Sucht nach vertrauenswürdigen Elementen
    • gnupg_import - Importiert einen Schlüssel
    • gnupg_init - Initialisiert eine Verbindung
    • gnupg_keyinfo - Gibt ein Array mit Informationen über alle Schlüssel zurück, die dem gegebenen Muster entsprechen
    • gnupg_listsignatures - Liefert eine Liste von Schlüsselsignaturen
    • gnupg_setarmor - Gepanzerte Ausgabe umschalten
    • gnupg_seterrormode - Setzt den Modus für error_reporting
    • gnupg_setsignmode - Setzt den Signierungs-Modus
    • gnupg_sign - Signiert einen übergebenen Text
    • gnupg_verify - Verifiziert einen signierten 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 - Konvertierung vom Gregorianischen Kalender zum Julianischen Datum
    • gzclose - Schließt einen geöffnete gz-Dateizeiger
    • gzcompress - Komprimiert einen String
    • gzdecode - Dekodiert eine gzip-komprimierte Zeichenkette
    • gzdeflate - Komprimiert eine Zeichenkette
    • gzencode - Create a gzip compressed string
    • gzeof - Prüft bei einem gz-Dateizeiger auf EOF
    • gzfile - Liest eine ganze gz-Datei in ein Array
    • gzgetc - Holt Zeichen vom gz-Dateizeiger
    • gzgets - Get line from file pointer
    • gzgetss - Holt eine Zeile vom gz-Dateizeiger und entfernt die HTML-Tags
    • gzinflate - Dekomprimiert eine komprimierte Zeichenkette
    • gzopen - Öffnet eine gz-Datei
    • gzpassthru - Gibt alle verbleibenden Daten eines gz-Dateizeigers aus
    • gzputs - Alias von gzwrite
    • gzread - Liest binary-safe aus einer gz-Datei
    • gzrewind - Setzt den gz-Dateizeiger auf den Anfang zurück
    • gzseek - Positioniert den gz-Dateizeiger
    • gztell - Ermittelt die aktuelle Position eines gz-Dateizeigers
    • gzuncompress - Dekomprimiert einen komprimierten String
    • gzwrite - Ausgabe in gz-komprimierte Dateien
  • h
    • hash - Berechnet den Hash einer Nachricht
    • 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 - Liefert eine Liste der verfügbaren Hashing-Algorithmen
    • hash_copy - Dupliziert einen Hash-Kontext
    • hash_equals - Timing attack safe string comparison
    • hash_file - Berechnet den Hash des Inhalts einer Datei
    • hash_final - Schließt einen schrittweisen Hashing-Vorgang ab und liefert sein Ergebnis
    • hash_hkdf - Generate a HKDF key derivation of a supplied key input
    • hash_hmac - Berechnet einen Hash mit Schlüssel unter Verwendung von HMAC
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - Berechnet einen Hash einer Datei mit Schlüssel unter Verwendung von HMAC
    • hash_init - Initialisiert einen schrittweisen Hashing-Kontext
    • hash_pbkdf2 - Generate a PBKDF2 key derivation of a supplied password
    • hash_update - Fügt Daten an einen aktiven Hash-Kontext an
    • hash_update_file - Fügt Daten aus einer Datei an einen aktiven Hash-Kontext an
    • hash_update_stream - Fügt Daten aus einem Stream an einen aktiven Hash-Kontext an
    • header - Sendet einen HTTP-Header in Rohform
    • headers_list - Liefert eine Liste der gesendeten (oder zum Senden vorbereiteten) Antwort-Header
    • headers_sent - Prüft, ob oder wo die Header bereits gesendet wurden
    • header_register_callback - Call a header function
    • header_remove - Remove previously set headers
    • hebrev - Konvertiert logischen hebräischen Text in sichtbaren Text
    • hebrevc - Konvertiert (natürlichen) hebräischen Text in sichtbaren Text inkl. Anpassung von Zeilenumbrüchen
    • hex2bin - Dekodiert einen hexadezimal kodierten Binärstring
    • hexdec - Wandelt von hexadezimal zu dezimal um
    • highlight_file - Syntax-Hervorhebung für eine Datei
    • highlight_string - Hervorhebung der Syntax einer Zeichenkette
    • 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 - Wandelt alle geeigneten Zeichen in entsprechende HTML-Entities um
    • htmlspecialchars - Wandelt Sonderzeichen in HTML-Entities um
    • htmlspecialchars_decode - Wandelt besondere HTML-Entities zurück in Zeichen um
    • html_entity_decode - Wandelt HTML-Entities in ihre entsprechenden Zeichen um
    • HTTP-Kontextoptionen - Liste der HTTP-Kontextoptionen
    • http:// - Accessing HTTP(s) URLs
    • http_build_query - Liefert einen URL-kodierten Query-String
    • http_response_code - Get or Set the HTTP response code
    • hypot - Berechnet die Länge der Hypotenuse eines rechtwinkligen Dreiecks
  • i
    • ibase_add_user - Fügt einen Benutzer zu einer Security-Datenbank hinzu
    • ibase_affected_rows - Gibt die Anzahl der Zeilen zurück, die von der vorherigen Abfrage betroffen waren
    • ibase_backup - Initiiert eine Sicherungsaufgabe im Service Manager und springt sofort zurück
    • ibase_blob_add - Fügt Daten in ein neues BLOB ein
    • ibase_blob_cancel - Bricht die Erstellung eines neuen BLOBs ab
    • ibase_blob_close - BLOB schließen
    • ibase_blob_create - Erstellt ein neues BLOB zum Hinzufügen von Daten
    • ibase_blob_echo - Ausgabe von BLOB-Inhalten an den Browser
    • ibase_blob_get - Holt sich len Bytes Daten aus dem offenen BLOB
    • ibase_blob_import - Erstellt ein BLOB, kopiert die Dateidaten hinein und schließt es
    • ibase_blob_info - Gibt die Blob-Länge und andere nützliche Informationen zurück
    • ibase_blob_open - Öffnet BLOB zum Abrufen von Datenteilen
    • ibase_close - Schließt eine Verbindung zu einer InterBase-Datenbank
    • ibase_commit - Schreibt eine Transaktion fest
    • ibase_commit_ret - Schreibt eine Transaktion fest, ohne diese zu schließen
    • ibase_connect - Öffnet eine Verbindung zu einer Datenbank
    • ibase_db_info - Fragt statistische Daten über eine Datenbank ab
    • ibase_delete_user - Löscht einen Benutzer aus einer Security-Datenbank
    • ibase_drop_db - Löscht eine Datenbank
    • ibase_errcode - Gibt einen Fehlercode zurück
    • ibase_errmsg - Gibt eine Fehlermeldung zurück
    • ibase_execute - Ausführen einer vorbereiteten Abfrage
    • ibase_fetch_assoc - Ruft eine Ergebniszeile aus einer Abfrage als assoziatives Array ab
    • ibase_fetch_object - Liest einen Datensatz einer InterBase-Datenbank als Objekt ein
    • ibase_fetch_row - Ruft eine Zeile aus einer InterBase-Datenbank ab
    • ibase_field_info - Ruft Informationen zu einem Feld ab
    • ibase_free_event_handler - Bricht einen registrierten Ereignishandler ab
    • ibase_free_query - Gibt den Speicher einer vorbereiteten Abfrage wieder frei
    • ibase_free_result - Gibt eine Ergebnismenge frei
    • ibase_gen_id - Inkrementiert den benannten Generator und gibt dessen neuen Wert zurück
    • ibase_maintain_db - Führt einen Wartungsbefehl auf dem Datenbankserver aus
    • ibase_modify_user - Ändert den Benutzer einer Security-Datenbank
    • ibase_name_result - Weist einer Ergebnismenge einen Namen zu
    • ibase_num_fields - Ermittelt die Anzahl der Felder einer Ergebnismenge
    • ibase_num_params - Gibt die Anzahl der Parameter in einer vorbereiteten Abfrage zurück
    • ibase_param_info - Gibt Informationen zu einem Parameter in einer vorbereiteten Abfrage zurück
    • ibase_pconnect - Öffnet eine persistente Verbindung zu einer InterBase-Datenbank
    • ibase_prepare - Bereitet eine Abfrage für späteres Binden der Parameter-Platzhalter und Ausführung vor
    • ibase_query - Führt eine Abfrage auf einer InterBase Datenbank aus
    • ibase_restore - Leitet eine Wiederherstellungsaufgabe im Service Manager ein und kehrt sofort zurück
    • ibase_rollback - Macht eine Transaktion rückgängig
    • ibase_rollback_ret - Macht eine Transaktion rückgängig, ohne diese zu schließen
    • ibase_server_info - Informationen zu einem Datenbankserver anfordern
    • ibase_service_attach - Verbindet mit dem Service-Manager
    • ibase_service_detach - Trennt die Verbindung zum Service-Manager
    • ibase_set_event_handler - Registriert eine Rückruffunktion, die aufgerufen werden soll, wenn Ereignisse auftreten
    • ibase_trans - Startet eine Transaktion
    • ibase_wait_event - Wartet, bis ein Ereignis von der Datenbank veröffentlicht wurde
    • iconv - Konvertiert eine Zeichenkette von einem Zeichensatz in einen anderen
    • iconv_get_encoding - Liefert die aktuelle Einstellung für die Zeichensatz-Konvertierung
    • iconv_mime_decode - Decodes a MIME header field
    • iconv_mime_decode_headers - Decodes multiple MIME header fields at once
    • iconv_mime_encode - Composes a MIME header field
    • iconv_set_encoding - Setzt die aktuelle Einstellung für die Zeichensatzkonvertierung
    • iconv_strlen - Returns the character count of string
    • iconv_strpos - Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos - Finds the last occurrence of a needle within a haystack
    • iconv_substr - Cut out part of a string
    • idate - Formatiert einen Teil der lokalen Zeit/des lokalen Datums als Integer
    • 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 - Legt fest, ob der Verbindungsabbruch eines Clients die Skript-Ausführung abbrechen soll
    • image2wbmp - Gibt das Bild im Browser oder einer Datei aus.
    • 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 - Zeichnet einen Bogen
    • imageavif - Gibt das Bild im Browser oder einer Datei aus.
    • imagebmp - Output a BMP image to browser or file
    • imagechar - Zeichnet ein horizontal ausgerichtetes Zeichen
    • imagecharup - Zeichnet ein vertikal ausgerichtetes Zeichen
    • imagecolorallocate - Alloziert eine Farbe für eine Grafik
    • imagecolorallocatealpha - Allocate a color for an image
    • imagecolorat - Liefert den Farbwert eines Bildpunktes
    • imagecolorclosest - Ermittelt den Index der Farbe, die der angegebenen Farbe am nächsten kommt
    • 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 - Löscht eine Farbdefinition
    • imagecolorexact - Ermittelt den Index-Wert der angegebenen Farbe
    • 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 - Ermittelt den Index-Wert der angegebenen Farbe oder die nächstmögliche Alternative dazu
    • imagecolorresolvealpha - Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset - Setzt die Farbe für den angegebenen Paletten-Index
    • imagecolorsforindex - Ermittelt die Farbwerte eines Palettenindex
    • imagecolorstotal - Ermittelt die Anzahl der Farben in der Palette eines Bildes
    • imagecolortransparent - Definiert eine Farbe als transparent
    • imageconvolution - Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy - Kopiert einen Bildausschnitt
    • 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 - Kopieren und Ändern der Größe eines Bild-Teiles
    • imagecreate - Erzeugt ein neues Palettenbild
    • imagecreatefromavif - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefrombmp - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromgd - Create a new image from GD file or 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 - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromjpeg - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefrompng - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromstring - Create a new image from the image stream in the string
    • imagecreatefromtga - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromwbmp - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromwebp - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromxbm - Erzeugt ein neues Bild aus einer Datei oder URL
    • imagecreatefromxpm - Erzeugt ein neues Bild aus einer Datei oder 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 - Zeichnet eine gestrichelte Linie
    • imagedestroy - Löscht ein Bild
    • imageellipse - Draw an ellipse
    • imagefill - Flutfüllung
    • imagefilledarc - Draw a partial arc and fill it
    • imagefilledellipse - Draw a filled ellipse
    • imagefilledpolygon - Zeichnet ein gefülltes Polygon
    • imagefilledrectangle - Zeichnet ein gefülltes Rechteck
    • imagefilltoborder - Füllt einen Bereich mit einer bestimmten Farbe
    • imagefilter - Applies a filter to an image
    • imageflip - Flips an image using a given mode
    • imagefontheight - Ermittelt die Höhe einer Schriftart
    • imagefontwidth - Ermittelt die Breite einer Schriftart
    • imageftbbox - Give the bounding box of a text using fonts via freetype2
    • imagefttext - Write text to the image using fonts using FreeType 2
    • imagegammacorrect - Wendet eine Gamma-Korrektur auf ein GD-Bild an
    • 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 - Gibt das Bild im Browser oder einer Datei aus.
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - Aktiviert oder Deaktiviert Interlacing
    • imageistruecolor - Finds whether an image is a truecolor image
    • imagejpeg - Gibt das Bild im Browser oder einer Datei aus.
    • imagelayereffect - Set the alpha blending flag to use layering effects
    • imageline - Zeichnet eine Linie
    • imageloadfont - Lädt eine neue Schriftart
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - Copy the palette from one image to another
    • imagepalettetotruecolor - Converts a palette based image to true color
    • imagepng - Ausgabe eines Bildes im Browser oder als Datei im PNG-Format
    • imagepolygon - Zeichnet ein Polygon
    • imagerectangle - Zeichnet ein Rechteck
    • imageresolution - Get or set the resolution of the image
    • imagerotate - Rotate an image with a given angle
    • imagesavealpha - Ob beim Speichern von Bildern vollständige Alphakanal-Information erhalten wird
    • 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 - Setzt ein einzelnes Pixel
    • imagesetstyle - Set the style for line drawing
    • imagesetthickness - Set the thickness for line drawing
    • imagesettile - Set the tile image for filling
    • imagestring - Zeichnet einen horizontalen String
    • imagestringup - Zeichnet einen vertikalen String
    • imagesx - Ermittelt die Breite eines Bildes
    • imagesy - Ermittelt die Höhe eines Bildes
    • imagetruecolortopalette - Convert a true color image to a palette image
    • imagettfbbox - Ermittelt das umgebende Rechteck eines Textes, der eine TrueType-Schriftart verwendet
    • imagettftext - Schreibt Text mit TrueType-Schriftarten ins Bild
    • imagetypes - Liefert die von der verwendeten PHP-Version unterstützten Grafikformate
    • imagewbmp - Gibt das Bild im Browser oder einer Datei aus.
    • 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 - Ruft grundlegende Merkmale eines Bildes ab
    • 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 - Konvertiert einen 8bit-String in einen quoted-printable String
    • imap_alerts - Liefert alle aufgetretenen IMAP-Alarmnachrichten
    • imap_append - Hängt eine String-Nachricht an ein Postfach an
    • imap_base64 - Dekodiert Base64-kodierten Text
    • imap_binary - Konvertiert einen 8bit-String in einen Base64-kodierten String
    • imap_body - Liefert den Textkörper einer Nachricht
    • imap_bodystruct - Liefert die Struktur eines bestimmten Nachrichtenteils
    • imap_check - Prüft das aktuelle Postfach
    • imap_clearflag_full - Löscht die Flags einer Nachricht
    • imap_close - Schließt einen IMAP-Stream
    • imap_create - Alias von imap_createmailbox
    • imap_createmailbox - Legt ein neues Postfach an
    • imap_delete - Markiert eine Nachricht im aktuellen Postfach zur Löschung
    • imap_deletemailbox - Löscht ein Postfach
    • imap_errors - Liefert alle bisher aufgetretenen Fehlermeldungen
    • imap_expunge - Löscht alle zum Löschen markierte Nachrichten
    • imap_fetchbody - Liefert einen bestimmten Abschnitt aus dem Textkörper einer Nachricht
    • imap_fetchheader - Liefert den Kopf einer Nachricht
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Liefert die Struktur einer Nachricht
    • imap_fetchtext - Alias von imap_body
    • imap_fetch_overview - Liefert eine Zusammenfassung der Kopfdaten von Nachrichten
    • imap_gc - Leert den IMAP-Cache
    • imap_getacl - Liefert die Liste der Zugriffsrechte (ACL) für ein Postfach
    • imap_getmailboxes - Liefert detaillierte Informationen zu allen Postfächern
    • imap_getsubscribed - Liefert die Liste aller abonnierten Postfächer
    • imap_get_quota - Liefert Quota-Einstellungen und Nutzungsstatistik der Postfächer
    • imap_get_quotaroot - Liefert die Quota-Einstellungen für ein Benutzerpostfach
    • imap_header - Alias von imap_headerinfo
    • imap_headerinfo - Liefert Informationen über die Kopfdaten einer Nachricht
    • imap_headers - Liefert die Kopfzeilen aller Nachrichten eines Postfachs
    • imap_is_open - Check if the IMAP stream is still valid
    • imap_last_error - Liefert den zuletzt aufgetretenen IMAP-Fehler
    • imap_list - Liefert die Liste der Postfächer
    • imap_listmailbox - Alias von imap_list
    • imap_listscan - Liefert eine Liste von Postfächern nach Suchkriterien
    • imap_listsubscribed - Alias von imap_lsub
    • imap_lsub - Liefert eine Liste aller abonnierten Postfächer
    • imap_mail - Sendet eine E-Mail-Nachricht
    • imap_mailboxmsginfo - Liefert Informationen zum aktuellen Postfach
    • imap_mail_compose - Erzeugt eine MIME-Nachricht aus Kopf- und Nachrichtenelementen
    • imap_mail_copy - Kopiert Nachrichten in ein Postfach
    • imap_mail_move - Verschiebt Nachrichten in ein anderes Postfach
    • imap_mime_header_decode - Dekodiert MIME-kodierte Kopfzeilen
    • imap_msgno - Liefert die Nummer einer Nachricht für eine gegebene UID
    • imap_mutf7_to_utf8 - Decode a modified UTF-7 string to UTF-8
    • imap_num_msg - Liefert die Anzahl der Nachrichten im aktuellen Postfach
    • imap_num_recent - Liefert die Anzahl der kürzlich eingetroffenen Nachrichten
    • imap_open - Öffnet einen IMAP-Stream zu einem Postfach
    • imap_ping - Prüft einen IMAP-Stream auf Funktionalität
    • imap_qprint - Konvertiert einen quoted-printable-kodierten String in einen 8-Bit-String
    • imap_rename - Alias von imap_renamemailbox
    • imap_renamemailbox - Ändert den Namen eines Postfachs
    • imap_reopen - Öffnet einen IMAP-Stream für ein anderes Postfach neu
    • imap_rfc822_parse_adrlist - Zerlegt einen String mit Mailadressen
    • imap_rfc822_parse_headers - Liest E-Mail-Kopfzeilen aus einem String aus
    • imap_rfc822_write_address - Liefert eine korrekt formatierte E-Mail-Adresse aus übergebenen Informationen
    • imap_savebody - Speichert einen Teil des Nachrichtentextes in einer Datei
    • imap_scan - Alias von imap_listscan
    • imap_scanmailbox - Alias von imap_listscan
    • imap_search - Liefert ein Array von Nachrichten, die den gegebenen Suchkriterien entsprechen
    • imap_setacl - Legt die ACL (Zugriffsrechte) für ein Postfach fest
    • imap_setflag_full - Setzt Nachrichtenflags
    • imap_set_quota - Legt die Größenbeschränkung für ein Postfach fest
    • imap_sort - Liefert und sortiert Nachrichten eines Postfachs
    • imap_status - Liefert Statusinformationen zum angegebenen Postfach
    • imap_subscribe - Abonniert ein Postfach
    • imap_thread - Liefert Nachrichten als Baum zusammenhängender Themenstränge
    • imap_timeout - Setzt oder liefert den Imap-Timeout
    • imap_uid - Liefert die UID für die gegebene Nachrichtennummer
    • imap_undelete - Nimmt eine bereits gesetzte Löschmarkierung einer Nachricht zurück
    • imap_unsubscribe - Beendet das Abonnement eines Postfachs
    • imap_utf7_decode - Dekodiert einen String im modifizierten UTF-7-Format
    • imap_utf7_encode - Kodiert ISO-8859-1 Text im modifizieren UTF-7-Format
    • imap_utf8 - Konvertiert Text nach UTF-8
    • imap_utf8_to_mutf7 - Encode a UTF-8 string to modified UTF-7
    • implode - Verbindet Array-Elemente zu einem String
    • inet_ntop - Konvertiert eine komprimierte IP-Adresse in ein menschenlesbares Format
    • inet_pton - Konvertiert eine IP-Adresse im menschenlesbaren Format in eine komprimierte in_addr-Darstellung
    • 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 - Alias von 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 - Integer-Division
    • interface_exists - Prüft, ob ein bestimmtes Interface definiert wurde
    • InternalIterator::current - Liefert das aktuelle Element
    • InternalIterator::key - Liefert den Schlüssel des aktuellen Elements
    • InternalIterator::next - Rückt zum nächsten Element vor
    • InternalIterator::rewind - Setzt den Iterator auf das erste Element zurück
    • InternalIterator::valid - Prüft, ob die aktuelle Position gültig ist
    • InternalIterator::__construct - Privater Konstruktor, um eine direkte Instanziierung zu verhindern
    • 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 - Get last code point passed over after advancing or receding the iterator
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::formatObject - Formats an object
    • IntlDateFormatter::getCalendar - Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Get copy of formatter's calendar object
    • IntlDateFormatter::getDateType - Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Get the error code from last operation
    • IntlDateFormatter::getErrorMessage - Get the error text from the last operation
    • IntlDateFormatter::getLocale - Get the locale used by formatter
    • IntlDateFormatter::getPattern - Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType - Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZone - Get formatter's timezone
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient - Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime - Parse string to a field-based time value
    • IntlDateFormatter::parse - Parse string to a timestamp value
    • IntlDateFormatter::setCalendar - Sets the calendar type used by the formatter
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Sets formatter's timezone
    • 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 - Get the current element
    • IntlIterator::key - Get the current key
    • IntlIterator::next - Move forward to the next element
    • IntlIterator::rewind - Rewind the iterator to the first element
    • IntlIterator::valid - Check if current position is valid
    • IntlPartsIterator::getBreakIterator - Get IntlBreakIterator backing this parts iterator
    • IntlRuleBasedBreakIterator::getBinaryRules - Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules - Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus - Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Get the status values from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::__construct - Create iterator from ruleset
    • IntlTimeZone::countEquivalentIDs - Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault - Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration - Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone - Create a timezone object for the given ID
    • IntlTimeZone::createTimeZoneIDEnumeration - Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone - Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID - Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName - Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings - Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID - Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode - Get last error code on the object
    • IntlTimeZone::getErrorMessage - Get last error message on the object
    • IntlTimeZone::getGMT - Create GMT (UTC) timezone
    • IntlTimeZone::getID - Get timezone ID
    • IntlTimeZone::getIDForWindowsID - Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset - Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset - Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getRegion - Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion - Get the timezone data version currently used by ICU
    • IntlTimeZone::getUnknown - Get the "unknown" time zone
    • IntlTimeZone::getWindowsID - Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules - Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone - Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime - Check if this time zone uses daylight savings time
    • 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 - Konvertiert einen Wert nach integer
    • in_array - Prüft, ob ein Wert in einem Array existiert
    • ip2long - Konvertiert eine gemäß IPv4-Protokoll angegebene IP-Adresse vom Punkt-Format in ein Long Integer
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags
    • isset - Prüft, ob eine Variable deklariert ist und sich von null unterscheidet
    • is_a - Prüft, ob ein Objekt vom angegebenen Typ oder untergeordneten Typ ist
    • is_array - Prüft, ob die Variable ein Array ist
    • is_bool - Prüft, ob eine Variable vom Typ boolean ist
    • is_callable - Prüft, ob ein Wert als Funktion aus dem aktuellen Bereich aufgerufen werden kann.
    • is_countable - Verify that the contents of a variable is a countable value
    • is_dir - Prüft, ob der angegebene Dateiname ein Verzeichnis ist
    • is_double - Alias von is_float
    • is_executable - Prüft, ob der Dateiname ausführbar ist
    • is_file - Prüft, ob der Dateiname eine reguläre Datei ist
    • is_finite - Prüft, ob eine Gleitkommazahl endlich ist
    • is_float - Prüft, ob eine Variable vom Typ float ist
    • is_infinite - Prüft, ob eine Gleitkommazahl unendlich ist
    • is_int - Prüft, ob eine Variable vom Typ int ist
    • is_integer - Alias von is_int
    • is_iterable - Verify that the contents of a variable is an iterable value
    • is_link - Prüft, ob der Dateiname ein symbolischer Link ist
    • is_long - Alias von is_int
    • is_nan - Prüft, ob eine Gleitkommazahl NAN ist
    • is_null - Prüft, ob eine Variable null enthält
    • is_numeric - Prüft, ob eine Variable eine Zahl oder ein numerischer String ist
    • is_object - Prüft, ob eine Variable vom Typ object ist
    • is_readable - Prüft, ob eine Datei existiert und lesbar ist
    • is_real - Alias von is_float
    • is_resource - Prüft, ob eine Variable vom Typ resource ist
    • is_scalar - Prüft, ob eine Variable skalar ist
    • is_soap_fault - Prüft, ob ein SOAP-Aufruf fehlgeschlagen ist
    • is_string - Prüft, ob Variable vom Typ string ist
    • is_subclass_of - Prüft ob ein Objekt von der angegebenen Klasse abstammt oder sie implementiert
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - Prüft, ob die Datei mittels HTTP-POST upgeloadet wurde
    • is_writable - Prüft, ob in eine Datei geschrieben werden kann
    • is_writeable - Alias von is_writable
    • Iterator::current - Liefert das aktuelle Element
    • Iterator::key - Liefert den Schlüssel des aktuellen Elements
    • Iterator::next - Rückt den Zeiger auf das nächste Element vor
    • Iterator::rewind - Setzt den Iterator auf das erste Element zurück
    • Iterator::valid - Prüft, ob die aktuelle Position zulässig ist
    • IteratorAggregate::getIterator - Ruft einen externen Iterator ab
    • 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 current element 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 - Copy the iterator into an array
  • j
    • jddayofweek - Bestimmt den Wochentag aus einem Julianischen Datum
    • jdmonthname - Liefert den Monatsnamen
    • jdtofrench - Konvertiert ein Julianisches Datum zum Kalender der Französischen Revolution
    • jdtogregorian - Wandelt eine julianische Tageszahl in ein gregorianischen Datum um
    • jdtojewish - Konvertierung vom Julianischen Datum zum Jüdischen Kalender
    • jdtojulian - Wandelt eine julianische Tageszahl in ein julianisches Kalenderdatum um
    • jdtounix - Konvertiert ein julianisches Datum in einen Unix-Timestamp
    • jewishtojd - Konvertiert vom Jüdischen Kalender zum Julianischen Datum
    • join - Alias von implode
    • jpeg2wbmp - Konvertiert eine JPEG-Bilddatei in eine WBMP-Bilddatei
    • JsonSerializable::jsonSerialize - Gibt die Daten an, die in JSON serialisiert werden sollen
    • json_decode - Dekodiert eine JSON-Zeichenkette
    • json_encode - Liefert die JSON-Darstellung eines Wertes
    • json_last_error - Gibt den letzten aufgetretenen Fehler zurück
    • json_last_error_msg - Liefert die Fehlermeldung des letzten Aufrufs von json_encode() oder json_decode()
    • json_validate - Checks if a string contains valid JSON
    • juliantojd - Konvertierung vom Julianischen Kalender zum Julianischen Datum
  • k
    • key - Liefert einen Schlüssel eines Arrays
    • key_exists - Alias von array_key_exists
    • Kontextparameter - Liste der Kontextparameter
    • krsort - Sortiert ein Array nach Schlüsseln in absteigender Reihenfolge
    • ksort - Sortiert ein Array nach Schlüsseln in aufsteigender Reihenfolge
  • l
    • lcfirst - Wandelt den ersten Buchstaben eines Strings in einen Kleinbuchstaben um
    • lcg_value - Kongruenzgenerator für Pseudozufallszahlen
    • lchgrp - Changes group ownership of symlink
    • lchown - Changes user ownership of symlink
    • ldap_8859_to_t61 - Übersetzt 8859-Zeichen in t61-Zeichen
    • ldap_add - Fügt einem LDAP-Verzeichnis Einträge hinzu
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - Anmeldung an einem LDAP-Verzeichnis
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - Alias von ldap_unbind
    • ldap_compare - Vergleicht den Wert eines Merkmals mit dem eines Eintrags
    • ldap_connect - Verbindet mit einem 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 - Liefert bei einer Suche die Anzahl der Einträge
    • ldap_count_references - Counts the number of references in a search result
    • ldap_delete - Löscht einen Eintrag aus einem Verzeichnis
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Konvertiert einen DN in ein benutzerfreundliches Namensformat
    • ldap_err2str - Konvertiert eine LDAP-Fehlernummer in einen Fehlertext
    • ldap_errno - Liefert die LDAP-Fehlernummer des letzten LDAP-Kommandos
    • ldap_error - Liefert die LDAP-Fehlermeldung des letzten LDAP-Kommandos
    • 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 - Trennt einen DN in seine Bestandteile
    • ldap_first_attribute - Liefert das erste Merkmal
    • ldap_first_entry - Liefert die Kennung des ersten Ergebnisses
    • ldap_first_reference - Liefert die erste Referenz
    • ldap_free_result - Gibt den Ergebnisspeicher frei
    • ldap_get_attributes - Liefert die Merkmale eines Eintrags aus einem Suchergebnis
    • ldap_get_dn - Liefert den DN eines Eintrags aus einem Suchergebnis
    • ldap_get_entries - Liefert alle Einträge aus einem Ergebnis
    • ldap_get_option - Liefert den aktuellen Wert einer gegebenen Option
    • ldap_get_values - Liefert alle Werte eines Eintrags aus einem Ergebnis
    • ldap_get_values_len - Liefert alle binären Werte eines Eintrags aus einem Ergebnis
    • ldap_list - Suche in einer Ebene
    • ldap_modify - Alias von ldap_mod_replace
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Fügt Merkmalswerte zum aktuellen Eintrag hinzu
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Löscht Merkmalswerte des aktuellen Eintrags
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Ersetzt Merkmalswerte durch neue Merkmalswerte
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Liefert das nächste Merkmal im Ergebnis
    • ldap_next_entry - Liefert den nächsten Eintrag eines Ergebnisses
    • ldap_next_reference - Holt die nächste Referenz
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extrahiert Informationen aus einem Referenz-Eintrag
    • ldap_parse_result - Extrahiert Informationen aus einem Ergebnis
    • ldap_read - Liest einen Eintrag
    • ldap_rename - Ändert den Namen eines Eintrags
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Sucht im LDAP-Baum
    • ldap_set_option - Setzt den Wert der gegebenen Option
    • ldap_set_rebind_proc - Setzt einen Callback für erneute Bindungen bei der Verweisverfolgung
    • ldap_sort - Sortiert LDAP-Ergebniseinträge clientseitig
    • ldap_start_tls - Startet TLS
    • ldap_t61_to_8859 - Übersetzt t61-Zeichen in 8859-Zeichen
    • ldap_unbind - Löst die Bindung zu einem LDAP-Verzeichnis
    • levenshtein - Berechnet die Levenshtein-Distanz zwischen zwei Strings
    • libxml_clear_errors - Clear libxml error buffer
    • libxml_disable_entity_loader - Disable the ability to load external entities
    • libxml_get_errors - Retrieve array of errors
    • libxml_get_external_entity_loader - Get the current external entity loader
    • libxml_get_last_error - Retrieve last error from libxml
    • libxml_set_external_entity_loader - Changes the default external entity loader
    • libxml_set_streams_context - Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors - Disable libxml errors and allow user to fetch error information as needed
    • LimitIterator::current - Get current element
    • LimitIterator::getPosition - Return the current position
    • LimitIterator::key - Get current key
    • LimitIterator::next - Move the iterator forward
    • LimitIterator::rewind - Rewind the iterator to the specified starting offset
    • LimitIterator::seek - Seek to the given position
    • LimitIterator::valid - Check whether the current element is valid
    • LimitIterator::__construct - Construct a LimitIterator
    • link - Erzeugt einen harten Link
    • linkinfo - Liefert Informationen über einen Link
    • list - Weist Variablen zu, als wären sie ein Array
    • 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 - Ermittelt die Formatierungsinformationen für Zahlen
    • localtime - Ermittelt die lokale Zeit
    • log - Natürlicher Logarithmus
    • log1p - Berechnet log(1 + Zahl) mit guter Genauigkeit, auch wenn Zahl nahe bei Null liegt
    • log10 - Dekadischer Logarithmus (Logarithmus zur Basis 10)
    • long2ip - Konvertiert eine Long-Integer-Adresse in einen String, der das (IPv4) Internet-Standard-Punktformat enthält ("Dotted-Format")
    • lstat - Sammelt Informationen über eine Datei oder einen symbolischen Link
    • ltrim - Entfernt Leerraum (oder andere Zeichen) vom Anfang eines Strings
    • Lua::assign - Assign a PHP variable to Lua
    • Lua::call - Call Lua functions
    • Lua::eval - Evaluate a string as Lua code
    • Lua::getVersion - The getversion purpose
    • Lua::include - Parse a Lua script file
    • Lua::registerCallback - Register a PHP function to Lua
    • Lua::__construct - Lua constructor
    • LuaClosure::__invoke - Invoke luaclosure
    • LuaSandbox::callFunction - Call a function in a Lua global variable
    • LuaSandbox::disableProfiler - Disable the profiler
    • LuaSandbox::enableProfiler - Enable the profiler.
    • LuaSandbox::getCPUUsage - Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage - Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage - Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport - Fetch profiler data
    • LuaSandbox::getVersionInfo - Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary - Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString - Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer - Pause the CPU usage timer
    • LuaSandbox::registerLibrary - Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit - Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit - Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer - Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction - Wrap a PHP callable in a LuaSandboxFunction
    • LuaSandboxFunction::call - Call a Lua function
    • LuaSandboxFunction::dump - Dump the function as a binary blob
    • LuaSandboxFunction::__construct - Unused
    • lzf_compress - LZF compression
    • lzf_decompress - LZF decompression
    • lzf_optimized_for - Determines what LZF extension was optimized for
  • m
    • mail - Sendet eine 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 - Bestimmt den Maximalwert
    • 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 - Make a string lowercase
    • 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 - Errechnet den MD5-Hash eines Strings
    • md5_file - Berechnet den MD5-Code einer Datei
    • 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 - Add an item under a new key
    • Memcached::addByKey - Add an item under a new key on a specific server
    • Memcached::addServer - Add a server to the server pool
    • Memcached::addServers - Add multiple servers to the server pool
    • Memcached::append - Append data to an existing item
    • Memcached::appendByKey - Append data to an existing item on a specific server
    • Memcached::cas - Compare and swap an item
    • Memcached::casByKey - Compare and swap an item on a specific server
    • Memcached::decrement - Decrement numeric item's value
    • Memcached::decrementByKey - Decrement numeric item's value, stored on a specific server
    • Memcached::delete - Delete an item
    • Memcached::deleteByKey - Delete an item from a specific server
    • Memcached::deleteMulti - Delete multiple items
    • Memcached::deleteMultiByKey - Delete multiple items from a specific server
    • Memcached::fetch - Fetch the next result
    • Memcached::fetchAll - Fetch all the remaining results
    • Memcached::flush - Invalidate all items in the cache
    • Memcached::get - Retrieve an item
    • Memcached::getAllKeys - Gets the keys stored on all the servers
    • Memcached::getByKey - Retrieve an item from a specific server
    • Memcached::getDelayed - Request multiple items
    • Memcached::getDelayedByKey - Request multiple items from a specific server
    • Memcached::getMulti - Retrieve multiple items
    • Memcached::getMultiByKey - Retrieve multiple items from a specific server
    • Memcached::getOption - Retrieve a Memcached option value
    • Memcached::getResultCode - Return the result code of the last operation
    • Memcached::getResultMessage - Return the message describing the result of the last operation
    • Memcached::getServerByKey - Map a key to a server
    • Memcached::getServerList - Get the list of the servers in the pool
    • Memcached::getStats - Get server pool statistics
    • Memcached::getVersion - Get server pool version info
    • Memcached::increment - Increment numeric item's value
    • Memcached::incrementByKey - Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent - Check if a persitent connection to memcache is being used
    • Memcached::isPristine - Check if the instance was recently created
    • Memcached::prepend - Prepend data to an existing item
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::quit - Close any open connections
    • Memcached::replace - Replace the item under an existing key
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::resetServerList - Clears all servers from the server list
    • Memcached::set - Store an item
    • Memcached::setByKey - Store an item on a specific server
    • Memcached::setMulti - Store multiple items
    • Memcached::setMultiByKey - Store multiple items on a specific server
    • Memcached::setOption - Set a Memcached option
    • Memcached::setOptions - Set Memcached options
    • Memcached::setSaslAuthData - Set the credentials to use for authentication
    • Memcached::touch - Set a new expiration on an item
    • Memcached::touchByKey - Set a new expiration on an item on a specific server
    • Memcached::__construct - Create a Memcached instance
    • 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 - Berechnet den Metaphone-Schlüssel eines Strings
    • method_exists - Prüft ob eine Methode innerhalb eines Objekts existiert
    • mhash - Berechnet einen Hash
    • mhash_count - Liefert die höchstmögliche Hash-ID
    • mhash_get_block_size - Liefert die Blockgröße des übergebenen Hashes
    • mhash_get_hash_name - Liefert den Namen eines Hashes
    • mhash_keygen_s2k - Generates a key
    • microtime - Liefert den aktuellen Unix-Zeitstempel mit Mikrosekunden
    • mime_content_type - Ermittelt den MIME-Typ des Inhalts einer Datei
    • min - Bestimmt den Minimalwert
    • mkdir - Erstellt ein Verzeichnis
    • mktime - Liefert den Unix-Zeitstempel für ein Datum
    • money_format - Formatiert eine Zahl als Währungs-Zeichenkette
    • 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 - Verschiebt eine hochgeladene Datei an einen neuen Ort
    • 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 - Legt eine Nachrichten-Warteschlange an oder hängt sich an existierende an
    • msg_queue_exists - Prüft, ob die Nachrichten-Warteschlange existiert
    • msg_receive - Liest eine Nachricht aus einer Nachrichten-Warteschlange aus
    • msg_remove_queue - Entfernt eine Nachrichten-Warteschlange
    • msg_send - Send a message to a message queue
    • msg_set_queue - Setzt Metadaten in der Datenstruktur der Nachrichten-Warteschlange
    • msg_stat_queue - Liefert Informationen zur Datenstruktur einer Nachrichten-Warteschlange
    • mt_getrandmax - Liefert den größtmöglichen Zufallswert
    • mt_rand - Erzeugt eine Zufallszahl nach dem Mersenne-Twister-Verfahren
    • mt_srand - Initialisiert den Mersenne-Twister-Zufallszahlengenerator
    • 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::$affected_rows - Liefert die Anzahl der Datensätze, die vom letzten MySQL-Vorgang betroffen waren
    • mysqli::$client_info - Liefert die Version des MySQL-Clients als Zeichenkette
    • mysqli::$client_version - Liefert die Version des MySQL-Clients als Integer
    • mysqli::$connect_errno - Liefert den Fehlercode des letzten Verbindungsversuchs
    • mysqli::$connect_error - Liefert eine Beschreibung des letzten Verbindungsfehlers
    • mysqli::$errno - Liefert den Fehlercode des letzten Funktionsaufrufs
    • mysqli::$error - Liefert eine Zeichenkette, die den letzten Fehler beschreibt
    • mysqli::$error_list - Liefert eine Liste der Fehler des zuletzt ausgeführten Befehls
    • mysqli::$field_count - Liefert die Anzahl der Spalten der letzten Abfrage
    • mysqli::$host_info - Liefert eine Zeichenkette, die den Typ der verwendeten Verbindung angibt
    • mysqli::$info - Ruft Informationen über die zuletzt ausgeführte Abfrage ab
    • mysqli::$insert_id - Liefert den Wert, der bei der letzten Anweisung für die AUTO_INCREMENT-Spalte erzeugt wurde
    • mysqli::$protocol_version - Liefert die Version des verwendeten MySQL-Protokolls
    • mysqli::$server_info - Liefert die Version des MySQL-Servers
    • mysqli::$server_version - Liefert die Version des MySQL-Servers als Integer
    • mysqli::$sqlstate - Liefert den SQLSTATE-Fehler der letzten MySQL-Operation
    • mysqli::$thread_id - Liefert die Thread-ID der aktuellen Verbindung
    • mysqli::$warning_count - Liefert die Anzahl der Warnungen, die durch die letzte Abfrage erzeugt wurden
    • mysqli::autocommit - Aktiviert oder deaktiviert das automatische Bestätigen von Datenbankänderungen
    • mysqli::begin_transaction - Startet eine Transaktion
    • mysqli::change_user - Ändert den Benutzer der angegebenen Datenbankverbindung
    • mysqli::character_set_name - Liefert den aktuellen Zeichensatz der Datenbankverbindung
    • mysqli::close - Schließt die zuvor geöffnete Datenbankverbindung
    • mysqli::commit - Bestätigt die aktuelle Transaktion
    • mysqli::debug - Führt Debugging-Operationen durch
    • mysqli::dump_debug_info - Schreibt Debugging-Informationen in die Logdatei
    • mysqli::escape_string - Alias von mysqli_real_escape_string
    • mysqli::execute_query - Bereitet eine SQL-Anweisung vor, bindet die Parameter und führt die Anweisung aus
    • mysqli::get_charset - Liefert ein Zeichensatz-Objekt
    • mysqli::get_connection_stats - Liefert Verbindungsstatistiken des Clients
    • mysqli::get_warnings - Ermittelt das Ergebnis von SHOW WARNINGS
    • mysqli::init - Initialisiert MySQLi und liefert ein Objekt zur Verwendung mit mysqli_real_connect()
    • mysqli::kill - Weist den Server an, einen MySQL-Thread zu beenden
    • mysqli::more_results - Prüft, ob es von einer Mehrfachabfrage noch weitere Abfrageergebnisse gibt
    • mysqli::multi_query - Führt eine oder mehrere Abfragen in einer Datenbank durch
    • mysqli::next_result - Bereitet das nächste Ergebnis von multi_query vor
    • mysqli::options - Setzt Optionen
    • mysqli::ping - Pingt eine Serververbindung an oder versucht eine neue Verbindung aufzubauen, wenn die Verbindung unterbrochen wurde
    • mysqli::poll - Überprüft den Status von Verbindungen
    • mysqli::prepare - Bereitet eine SQL-Anweisung zur Ausführung vor
    • mysqli::query - Führt eine Abfrage in einer Datenbank durch
    • mysqli::real_connect - Baut eine Verbindung zu einem MySQL-Server auf
    • mysqli::real_escape_string - Maskiert Sonderzeichen in einer Zeichenkette zur Verwendung in einer SQL-Anweisung, wobei der aktuelle Zeichensatz der Verbindung berücksichtigt wird
    • mysqli::real_query - Führt eine SQL-Abfrage aus
    • mysqli::reap_async_query - Ruft das Ergebnis einer asynchronen Abfrage ab
    • mysqli::refresh - Führt ein Refresh durch
    • mysqli::release_savepoint - Entfernt einen benannten Sicherungspunkt aus der Menge der Sicherungspunkte der aktuellen Transaktion
    • mysqli::rollback - Macht die aktuelle Transaktion rückgängig
    • mysqli::savepoint - Sezt einen benannten Sicherungspunkt für eine Transaktion
    • mysqli::select_db - Legt die standardmäßige Datenbank für Datenbankabfragen fest
    • mysqli::set_charset - Legt den Standard-Zeichensatz des Clients fest
    • mysqli::set_opt - Alias von mysqli_options
    • mysqli::ssl_set - Wird beim Aufbau sicherer Verbindungen mit SSL verwendet
    • mysqli::stat - Liefert den aktuellen Systemstatus
    • mysqli::stmt_init - Initialisiert eine Anweisung und liefert ein Objekt für die Verwendung mit mysqli_stmt_prepare
    • mysqli::store_result - Überträgt die Ergebnismenge der letzten Abfrage
    • mysqli::thread_safe - Gibt an, ob Thread-Sicherheit gegeben ist oder nicht
    • mysqli::use_result - Initiiert den Abruf einer Ergebnismenge
    • mysqli::__construct - Baut eine neue Verbindung zum MySQL-Server auf
    • mysqli_connect - Alias von mysqli::__construct
    • mysqli_driver::$report_mode - Legt den Modus für die mysqli-Fehlermeldungen fest
    • mysqli_driver::embedded_server_end - Stoppt den eingebauten Server
    • mysqli_driver::embedded_server_start - Initialisiert und startet den eingebauten Server
    • mysqli_execute - Alias von mysqli_stmt_execute
    • mysqli_get_client_stats - Liefert prozessbezogene Client-Statistiken
    • mysqli_get_links_stats - Liefert Informationen über offene und zwischengespeicherte Verbindungen
    • mysqli_report - Alias von mysqli_driver->report_mode
    • mysqli_result::$current_field - Ermittelt den aktuellen Spalten-Offset eines Ergebniszeigers
    • mysqli_result::$field_count - Ermittelt die Anzahl der Spalten in der Ergebnismenge
    • mysqli_result::$lengths - Liefert die Breiten der Spalten der aktuellen Zeile einer Ergebnismenge
    • mysqli_result::$num_rows - Ermittelt die Anzahl der Zeilen einer Ergebnismenge
    • mysqli_result::data_seek - Verschiebt den Ergebniszeiger auf die angegebene Zeile
    • mysqli_result::fetch_all - Ruft alle Ergebniszeilen als assoziatives und/oder numerisches Array ab
    • mysqli_result::fetch_array - Ruft die nächste Zeile einer Ergebnismenge als assoziatives und/oder numerisches Array ab
    • mysqli_result::fetch_assoc - Ruft die nächste Zeile einer Ergebnismenge als assoziatives Array ab
    • mysqli_result::fetch_column - Ruft eine einzelne Spalte aus der nächsten Zeile einer Ergebnismenge ab
    • mysqli_result::fetch_field - Liefert die Metadaten der nächsten Spalte einer Ergebnismenge
    • mysqli_result::fetch_fields - Liefert ein Array von Objekten, die die Spalten einer Ergebnismenge darstellen
    • mysqli_result::fetch_field_direct - Ruft die Metadaten für eine einzelne Spalte ab
    • mysqli_result::fetch_object - Liefert die nächste Zeile einer Ergebnismenge als Objekt
    • mysqli_result::fetch_row - Liefert die nächste Zeile einer Ergebnismenge als numerisches Array
    • mysqli_result::field_seek - Setzt den Ergebniszeiger auf die angegebene Spalte
    • mysqli_result::free - Gibt den mit einem Ergebnis verbundenen Speicher frei
    • mysqli_result::getIterator - Ruft einen externen Iterator ab
    • mysqli_result::__construct - Erstellt ein mysqli_result-Objekt
    • mysqli_sql_exception::getSqlState - Liefert den SQLSTATE-Fehlercode
    • mysqli_stmt::$affected_rows - Liefert die gesamte Anzahl der Datensätze, die bei der letzten ausgeführten Anweisung geändert, gelöscht, eingefügt oder abgeglichen wurden
    • mysqli_stmt::$errno - Liefert den Fehlercode der zuletzt aufgerufenen Anweisung
    • mysqli_stmt::$error - Liefert die Beschreibung des letzten Fehlers einer Anweisung als Zeichenkette
    • mysqli_stmt::$error_list - Liefert eine Liste der Fehler der zuletzt ausgeführten Anweisung
    • mysqli_stmt::$field_count - Liefert die Anzahl der Spalten in der angegebenen Anweisung
    • mysqli_stmt::$insert_id - Ermittelt die ID, die beim letzten INSERT-Vorgang erzeugt wurde
    • mysqli_stmt::$num_rows - Liefert die Anzahl der vom Server abgerufenen Datensätze
    • mysqli_stmt::$param_count - Liefert die Anzahl der Parameter einer Anweisung
    • mysqli_stmt::$sqlstate - Liefert den SQLSTATE-Fehlercode der letzten Anweisung
    • mysqli_stmt::attr_get - Liefert den aktuellen Wert des Attributs einer Anweisung
    • mysqli_stmt::attr_set - Verändert das Verhalten einer vorbereiteten Anweisung (prepared statement)
    • mysqli_stmt::bind_param - Bindet Variablen als Parameter an eine vorbereitete Anweisung (prepared statement)
    • mysqli_stmt::bind_result - Bindet Variablen an eine vorbereitete Anweisung (prepared statement), um das Ergebnis einer Abfrage abzulegen
    • mysqli_stmt::close - Schließt eine vorbereitete Anweisung (prepared statement)
    • mysqli_stmt::data_seek - Verschiebt den Ergebniszeiger auf eine beliebige Zeile im gepufferten Ergebnis
    • mysqli_stmt::execute - Führt eine vorbereitete Anweisung aus
    • mysqli_stmt::fetch - Ruft Ergebnisse aus einer vorbereiteten Anweisung in gebundene Variablen ab
    • mysqli_stmt::free_result - Gibt den mit der angegebenen Anweisung verbundenen Ergebnisspeicher frei
    • mysqli_stmt::get_result - Ruft die Ergebnismenge aus einer vorbereiteten Anweisung als mysqli_result-Objekt ab
    • mysqli_stmt::get_warnings - Ermittelt das Ergebnis von SHOW WARNINGS
    • mysqli_stmt::more_results - Prüft, ob es weitere Ergebnisse aus einer Mehrfachabfrage gibt
    • mysqli_stmt::next_result - Liest das nächste Ergebnis einer Mehrfachabfrage aus
    • mysqli_stmt::prepare - Bereitet eine SQL-Anweisung zur Ausführung vor
    • mysqli_stmt::reset - Setzt eine vorbereitete Anweisung zurück
    • mysqli_stmt::result_metadata - Liefert die Metadaten der Ergebnismenge aus einer vorbereiteten Anweisung
    • mysqli_stmt::send_long_data - Sendet Daten blockweise
    • mysqli_stmt::store_result - Speichert eine Ergebnismenge in einem internen Puffer
    • mysqli_stmt::__construct - Erzeugt ein neues mysqli_stmt-Objekt
    • mysqli_warning::next - Ruft die nächste Warnung ab
    • mysqli_warning::__construct - Privater Konstruktor, um eine direkte Instanziierung zu verhindern
    • mysql_affected_rows - Liefert die Anzahl betroffener Datensätze einer vorhergehenden MySQL-Operation
    • mysql_client_encoding - Liefert den Namen des Zeichensatzes
    • mysql_close - Schließt eine Verbindung zu MySQL
    • mysql_connect - Öffnet eine Verbindung zu einem MySQL-Server
    • mysql_create_db - Legt eine MySQL-Datenbank an
    • mysql_data_seek - Bewegt den internen Ergebnis-Zeiger
    • mysql_db_name - Liefert den Namen einer Datenbank vom mysql_list_dbs-Aufruf
    • mysql_db_query - Wählt eine Datenbank aus und führt darauf eine Abfrage aus
    • mysql_drop_db - Löscht eine Datenbank
    • mysql_errno - Liefert die Nummer einer Fehlermeldung einer zuvor ausgeführten MySQL-Operation
    • mysql_error - Liefert den Fehlertext der zuvor ausgeführten MySQL-Operation
    • mysql_escape_string - Maskiert eine Zeichenkette zur Verwendung in einer MySQL-Abfrage
    • mysql_fetch_array - Liefert einen Datensatz als assoziatives Array, als numerisches Array oder beides
    • mysql_fetch_assoc - Liefert einen Datensatz als assoziatives Array
    • mysql_fetch_field - Liefert ein Objekt mit Spalteninformationen aus einem Abfrageergebnis
    • mysql_fetch_lengths - Liefert die Längen aller Felder aus einem Ergebnis
    • mysql_fetch_object - Liefert eine Ergebniszeile als Objekt
    • mysql_fetch_row - Liefert einen Datensatz als indiziertes Array
    • mysql_field_flags - Liefert die Flags des angegebenen Feldes aus einem Abfrageergebnis
    • mysql_field_len - Liefert die Länge des angegebenen Feldes
    • mysql_field_name - Liefert den Namen des angegebenen Feldes aus einem Ergebnis
    • mysql_field_seek - Setzt den Ergebniszeiger auf einen bestimmten Feldoffset
    • mysql_field_table - Liefert den Namen der Tabelle, die das genannte Feld enthält
    • mysql_field_type - Liefert den Typ des spezifizierten Feldes aus einem Ergebnis
    • mysql_free_result - Gibt belegten Speicher wieder frei
    • mysql_get_client_info - Liefert MySQL-Clientinformationen
    • mysql_get_host_info - Liefert Informationen zum MySQL-Host
    • mysql_get_proto_info - Liefert MySQL-Protokollinformationen
    • mysql_get_server_info - Liefert Informationen zum MySQL-Server
    • mysql_info - Liefert Informationen über die zuletzt ausgeführte Anfrage
    • mysql_insert_id - Liefert die ID, die in der vorherigen Abfrage erzeugt wurde
    • mysql_list_dbs - Listet die verfügbaren Datenbanken (Schemata) auf einem MySQL-Server auf
    • mysql_list_fields - Listet MySQL-Tabellenfelder auf
    • mysql_list_processes - Zeigt die MySQL-Prozesse an
    • mysql_list_tables - Listet Tabellen einer MySQL-Datenbank auf
    • mysql_num_fields - Liefert die Anzahl der Felder in einem Ergebnis
    • mysql_num_rows - Liefert die Anzahl der Zeilen in einem Ergebnis
    • mysql_pconnect - Öffnet eine persistente Verbindung zum MySQL-Server
    • mysql_ping - Pingt eine Serververbindung an und verbindet erneut, wenn keine Verbindung besteht
    • mysql_query - Sendet eine Abfrage an MySQL
    • mysql_real_escape_string - Maskiert spezielle Zeichen innerhalb einer Zeichenkette für die Verwendung in einer SQL-Anweisung
    • mysql_result - Liefert eine Spalte aus einem MySQL-Ergebnis
    • mysql_select_db - Wählt eine MySQL-Datenbank aus
    • mysql_set_charset - Setzt den Verbindungszeichensatz
    • mysql_stat - Zeigt den momentanen Serverstatus an
    • mysql_tablename - Liefert den Namen einer Tabelle
    • mysql_thread_id - Zeigt die aktuelle Thread-ID an
    • mysql_unbuffered_query - Sendet eine SQL-Anfrage an MySQL, ohne Ergebniszeilen abzuholen und zu puffern
    • mysql_xdevapi\Client::close - Schließt die Client-Verbindung
  • n
    • natcasesort - Sortiert ein Array in "natürlicher Reihenfolge", Groß/Kleinschreibung wird ignoriert
    • natsort - Sortiert ein Array in "natürlicher Reihenfolge"
    • net_get_interfaces - Get network interfaces
    • next - Rückt den internen Arrayzeiger vor
    • ngettext - Pluralversion von gettext
    • nl2br - Fügt vor allen Zeilenumbrüchen eines Strings HTML-Zeilenumbrüche ein
    • nl_langinfo - Query-Language und 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 - Checks if the provided string is already in the specified normalization form
    • Normalizer::normalize - Normalizes the input provided and returns the normalized string
    • NumberFormatter::create - Create a number formatter
    • NumberFormatter::format - Format a number
    • NumberFormatter::formatCurrency - Format a currency value
    • NumberFormatter::getAttribute - Get an attribute
    • NumberFormatter::getErrorCode - Get formatter's last error code
    • NumberFormatter::getErrorMessage - Get formatter's last error message
    • NumberFormatter::getLocale - Get formatter locale
    • NumberFormatter::getPattern - Get formatter pattern
    • NumberFormatter::getSymbol - Get a symbol value
    • NumberFormatter::getTextAttribute - Get a text attribute
    • NumberFormatter::parse - Parse a number
    • NumberFormatter::parseCurrency - Parse a currency number
    • NumberFormatter::setAttribute - Set an attribute
    • NumberFormatter::setPattern - Set formatter pattern
    • NumberFormatter::setSymbol - Set a symbol value
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - Formatiert eine Zahl mit Tausender-Trennzeichen
  • 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 - Kodiert eine URI nach RFC 3986
    • ob_clean - Löscht den Inhalt des aktiven Ausgabepuffer
    • ob_end_clean - Löscht den Inhalt des aktiven Ausgabepuffers und deaktiviert ihn
    • ob_end_flush - Leert (sendet) den Rückgabewert des aktiven Ausgabe-Handlers und deaktiviert den aktiven Ausgabepuffer
    • ob_flush - Leert (sendet) den Rückgabewert des aktiven Ausgabe-Handlers
    • ob_get_clean - Get the contents of the active output buffer and turn it off
    • ob_get_contents - Liefert den Inhalt des Ausgabepuffers
    • ob_get_flush - Flush (send) the return value of the active output handler, return the contents of the active output buffer and turn it off
    • ob_get_length - Return the length of the output buffer
    • ob_get_level - Anzahl der aktiven Ausgabepuffer
    • ob_get_status - Get status of output buffers
    • ob_gzhandler - ob_start callback function to gzip output buffer
    • ob_iconv_handler - Konvertiert Zeichensatzkodierung als Ausgabepuffer-Handler (output buffer handler)
    • ob_implicit_flush - Schaltet die implizite Ausgabe ein bzw. aus
    • ob_list_handlers - List all output handlers in use
    • ob_start - Ausgabepufferung aktivieren
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • ocibindbyname - Alias von oci_bind_by_name
    • ocicancel - Alias von oci_cancel
    • ocicloselob - Alias von OCILob::close
    • ocicollappend - Alias von OCICollection::append
    • ocicollassign - Alias von OCICollection::assign
    • ocicollassignelem - Alias von OCICollection::assignElem
    • OCICollection::append - Hängt ein Element an eine Sammlung
    • OCICollection::assign - Weist einer Sammlung einen Wert aus einer anderen Sammlung zu
    • OCICollection::assignElem - Weist einem Element einer Sammlung einen Wert zu
    • OCICollection::free - Gibt die mit einem Sammelobjekt verknüpften Ressourcen frei
    • OCICollection::getElem - Liefert den Wert eines Elements
    • OCICollection::max - Liefert die maximale Anzahl der Elemente in einer Sammlung
    • OCICollection::size - Liefert die Größe der Sammlung
    • OCICollection::trim - Entfernt Elemente vom Ende einer Sammlung
    • ocicollgetelem - Alias von OCICollection::getElem
    • ocicollmax - Alias von OCICollection::max
    • ocicollsize - Alias von OCICollection::size
    • ocicolltrim - Alias von OCICollection::trim
    • ocicolumnisnull - Alias von oci_field_is_null
    • ocicolumnname - Alias von oci_field_name
    • ocicolumnprecision - Alias von oci_field_precision
    • ocicolumnscale - Alias von oci_field_scale
    • ocicolumnsize - Alias von oci_field_size
    • ocicolumntype - Alias von oci_field_type
    • ocicolumntyperaw - Alias von oci_field_type_raw
    • ocicommit - Alias von oci_commit
    • ocidefinebyname - Alias von oci_define_by_name
    • ocierror - Alias von oci_error
    • ociexecute - Alias von oci_execute
    • ocifetch - Alias von oci_fetch
    • ocifetchinto - Veraltete Variante von oci_fetch_array, oci_fetch_object, oci_fetch_assoc und oci_fetch_row
    • ocifetchstatement - Alias von oci_fetch_all
    • ocifreecollection - Alias von OCICollection::free
    • ocifreecursor - Alias von oci_free_statement
    • ocifreedesc - Alias von OCILob::free
    • ocifreestatement - Alias von oci_free_statement
    • ociinternaldebug - Alias von oci_internal_debug
    • ociloadlob - Alias von 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 - Alias von OCILob::import
    • OCILob::seek - Sets the internal pointer of the large object
    • OCILob::setBuffering - Changes current state of buffering for the large object
    • OCILob::size - Returns size of large object
    • OCILob::tell - Returns the current position of internal pointer of large object
    • OCILob::truncate - Truncates large object
    • OCILob::write - Writes data to the large object
    • OCILob::writeTemporary - Writes a temporary large object
    • OCILob::writeToFile - Alias von OCILob::export
    • ocilogoff - Alias von oci_close
    • ocilogon - Alias von oci_connect
    • ocinewcollection - Alias von oci_new_collection
    • ocinewcursor - Alias von oci_new_cursor
    • ocinewdescriptor - Alias von oci_new_descriptor
    • ocinlogon - Alias von oci_new_connect
    • ocinumcols - Alias von oci_num_fields
    • ociparse - Alias von oci_parse
    • ociplogon - Alias von oci_pconnect
    • ociresult - Alias von oci_result
    • ocirollback - Alias von oci_rollback
    • ocirowcount - Alias von oci_num_rows
    • ocisavelob - Alias von OCILob::save
    • ocisavelobfile - Alias von OCILob::import
    • ociserverversion - Alias von oci_server_version
    • ocisetprefetch - Alias von oci_set_prefetch
    • ocistatementtype - Alias von oci_statement_type
    • ociwritelobtofile - Alias von OCILob::export
    • ociwritetemporarylob - Alias von OCILob::writeTemporary
    • oci_bind_array_by_name - Bindet ein PHP-Array an einen Oracle-PL/SQL-Arrayparameter
    • oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
    • oci_cancel - Bricht das Lesen eines Zeigers ab
    • oci_client_version - Returns the Oracle client library version
    • oci_close - Schließt eine Oracle-Verbindung
    • 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 - Liefert den letzten Fehler
    • oci_execute - Executes a statement
    • oci_fetch - Ruft die nächste Zeile einer Abfrage in einen internen Puffer ab
    • oci_fetch_all - Ruft mehrere Datensätze einer Abfrage in ein zweidimensionales Array ab
    • oci_fetch_array - Liefert die nächste Zeile einer Abfrage als assoziatives oder numerisches Array
    • oci_fetch_assoc - Liefert die nächste Zeile einer Abfrage als assoziatives Array
    • oci_fetch_object - Liefert die nächste Zeile einer Abfrage als Objekt
    • oci_fetch_row - Liefert die nächste Zeile einer Abfrage als numerisches 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 - Gibt alle verknüpften Ressourcen eines Statements oder Zeigers frei.
    • 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 - Wandelt von oktal zu dezimal um
    • odbc_autocommit - Ändert das Autocommit-Verhalten
    • odbc_binmode - Behandlung von Binärdaten
    • odbc_close - Schließ eine ODBC-Verbindung
    • odbc_close_all - Schließt alle ODBC-Verbindungen
    • odbc_columnprivileges - Liste Spalten und damit verbundene Rechte für die angegeben Tabelle auf
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Schließt eine ODBC-Transaktion ab
    • odbc_connect - Verbindet mit einer Datenquelle
    • 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 - Liefert den Cursornamen
    • odbc_data_source - Returns information about available DSNs
    • odbc_do - Alias von odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Führt einen SQL-Befehl direkt aus
    • odbc_execute - Führt einen vorbereiteten SQL-Befehl aus
    • odbc_fetch_array - Fetch a result row as an associative array
    • odbc_fetch_into - Liest eine Ergebniszeile in ein Array
    • odbc_fetch_object - Fetch a result row as an object
    • odbc_fetch_row - Liefert eine Zeile zurück
    • odbc_field_len - Bestimmt die Länge (Präzision) eines Feldes
    • odbc_field_name - Liefert den Spaltennamen
    • odbc_field_num - Liefert die Spaltennummer
    • odbc_field_precision - Alias von odbc_field_len
    • odbc_field_scale - Get the scale of a field
    • odbc_field_type - Datentyp eines Feldes
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Gibt den durch ein Abfrageergebnis belegten Speicher wieder frei
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Steuert die Behandlung von LONG-Spalten
    • odbc_next_result - Checks if multiple results are available
    • odbc_num_fields - Liefert die Anzahl der Ergebnisspalten
    • odbc_num_rows - Liefert die Zeilenzahl des Abfrageergebnisses
    • odbc_pconnect - Öffnet eine persistente Datenbankverbindung
    • odbc_prepare - Bereitet eine Anweisung für die Ausführung vor
    • 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 - Liefert Ergebnisdaten
    • odbc_result_all - Gibt das aktuelle Abfrageergebnis als HTML-Tabelle aus
    • odbc_rollback - Bricht eine Transaktion ab
    • odbc_setoption - ODBC-Einstellungen anpassen
    • 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:// - Audio streams
    • opcache_compile_file - Compiles and caches a PHP script without executing it
    • opcache_get_configuration - Get configuration information about the cache
    • opcache_get_status - Liefert Statusinformationen über den Opcode-Cache
    • opcache_invalidate - Invalidates a cached script
    • opcache_is_script_cached - Tells whether a script is cached in OPCache
    • opcache_reset - Setzt den Inhalt des Opcode-Caches zurück
    • 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 - Öffnet ein Verzeichnis-Handle
    • openlog - Stellt eine Verbindung zum Log-Dienst des Systems her
    • 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 - Exportiert einen CSR als Zeichenkette
    • openssl_csr_export_to_file - Exportiert einen CSR in eine Datei
    • openssl_csr_get_public_key - Liefert den öffentlichen Schlüssel eines CSR
    • openssl_csr_get_subject - Liefert das Subjekt eines CSR
    • openssl_csr_new - Erzeugt einen CSR
    • openssl_csr_sign - Signiert einen CSR mit einem anderen Zertifikat (oder sich selbst) und generiert ein Zertifikat
    • 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 - Verschlüsselt Daten
    • openssl_error_string - Liefert eine OpenSSL-Fehlermeldung
    • openssl_free_key - Gibt eine Schlüssel-Ressource frei
    • 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 - Alias von openssl_pkey_get_private
    • openssl_get_publickey - Alias von openssl_pkey_get_public
    • openssl_open - Öffnet versiegelte Daten
    • openssl_pbkdf2 - Generates a PKCS5 v2 PBKDF2 string
    • openssl_pkcs7_decrypt - Entschlüsselt eine S/MIME-verschlüsselte Nachricht
    • openssl_pkcs7_encrypt - Verschlüsselt eine S/MIME-Nachricht
    • openssl_pkcs7_read - Export the PKCS7 file to an array of PEM certificates
    • openssl_pkcs7_sign - Signiert eine S/MIME-Nachricht
    • openssl_pkcs7_verify - Überprüft die Signatur einer mit S/MIME signierten Nachricht
    • openssl_pkcs12_export - Exportiert eine PKCS#12-kompatible Zertifikats-Datei in eine Variable
    • openssl_pkcs12_export_to_file - Exportiert in eine PKCS#12-kompatible Zertifikats-Datei
    • openssl_pkcs12_read - Parst eine PKCS#12-Zertifikats-Datei in ein Array
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - Speichert ein exportierbares Format eines Schlüssels in einer Zeichenkette
    • openssl_pkey_export_to_file - Speichert einen Schlüssel in einem exportierbaren Format in einer Datei
    • openssl_pkey_free - Gibt einen privaten Schlüssel frei
    • openssl_pkey_get_details - Liefert ein Array mit Schlüssel-Details
    • openssl_pkey_get_private - Liefert einen privaten Schlüssel
    • openssl_pkey_get_public - Extrahiert einen öffentlichen Schlüssel aus einem Zertifikat und bereitet diesen zur Verwendung vor
    • openssl_pkey_new - Erzeugt einen neuen privaten Schlüssel
    • openssl_private_decrypt - Entschlüsselt Daten mit einem privaten Schlüssel
    • openssl_private_encrypt - Verschlüsselt Daten mit einem privaten Schlüssel
    • openssl_public_decrypt - Entschlüsselt Daten mit einem öffentlichen Schlüssel
    • openssl_public_encrypt - Verschlüsselt Daten mit einem öffentlichen Schlüssel
    • openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
    • openssl_seal - Versiegelt (verschlüsselt) Daten
    • openssl_sign - Erzeugt eine Signatur
    • 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 - Überprüft eine Signatur
    • openssl_x509_checkpurpose - Überprüft, ob ein Zertifikat für einen bestimmten Zweck verwendet werden kann
    • openssl_x509_check_private_key - Überprüft, ob ein privater Schlüssel zu einem Zertifikat passt
    • openssl_x509_export - Exportiert ein Zertifikat als Zeichenkette
    • openssl_x509_export_to_file - Exportiert ein Zertifikat in eine Datei
    • openssl_x509_fingerprint - Calculates the fingerprint, or digest, of a given X.509 certificate
    • openssl_x509_free - Gibt eine Zertifikats-Ressource frei
    • openssl_x509_parse - Parst ein X.509-Zertifikat und liefert die Informationen als Array
    • openssl_x509_read - Parst ein X.509-Zertitifikat und gibt ein Objekt dafür zurück
    • openssl_x509_verify - Verifies digital signature of x509 certificate against a public key
    • ord - Konvertiert das erste Byte einer Zeichenkette in einen Wert zwischen 0 und 255
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry
    • output_add_rewrite_var - Fügt Werte zum URL-Rewriter hinzu
    • output_reset_rewrite_vars - Reset URL rewriter values
    • Override::__construct - Erstellt eine neue Instanz des Attributs Override
  • p
    • pack - Packt Daten in eine binäre Zeichenkette
    • parallel\bootstrap - Bootstrapping
    • parallel\Channel::close - Closing
    • parallel\Channel::make - Access
    • parallel\Channel::open - Access
    • parallel\Channel::recv - Sharing
    • parallel\Channel::send - Sharing
    • parallel\Channel::__construct - Channel Construction
    • parallel\Events::addChannel - Targets
    • parallel\Events::addFuture - Targets
    • parallel\Events::poll - Polling
    • parallel\Events::remove - Targets
    • parallel\Events::setBlocking - Behaviour
    • parallel\Events::setInput - Input
    • parallel\Events::setTimeout - Behaviour
    • parallel\Events\Input::add - Inputs
    • parallel\Events\Input::clear - Inputs
    • parallel\Events\Input::remove - Inputs
    • parallel\Future::cancel - Cancellation
    • parallel\Future::cancelled - State Detection
    • parallel\Future::done - State Detection
    • parallel\Future::value - Resolution
    • parallel\run - Execution
    • parallel\Runtime::close - Runtime Graceful Join
    • parallel\Runtime::kill - Runtime Join
    • parallel\Runtime::run - Execution
    • parallel\Runtime::__construct - Runtime Construction
    • parallel\Sync::get - Access
    • parallel\Sync::notify - Synchronization
    • parallel\Sync::set - Access
    • parallel\Sync::wait - Synchronization
    • parallel\Sync::__construct - Construction
    • parallel\Sync::__invoke - Synchronization
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Return the inner iterator's children contained in a ParentIterator
    • ParentIterator::hasChildren - Check whether the inner iterator's current element has children
    • ParentIterator::next - Move the iterator forward
    • ParentIterator::rewind - Rewind the iterator
    • ParentIterator::__construct - Constructs a ParentIterator
    • Parle\Lexer::advance - Process next lexer rule
    • Parle\Lexer::build - Finalize the lexer rule set
    • Parle\Lexer::callout - Define token callback
    • Parle\Lexer::consume - Pass the data for processing
    • Parle\Lexer::dump - Dump the state machine
    • Parle\Lexer::getToken - Retrieve the current token
    • Parle\Lexer::insertMacro - Insert regex macro
    • Parle\Lexer::push - Add a lexer rule
    • Parle\Lexer::reset - Reset lexer
    • Parle\Parser::advance - Process next parser rule
    • Parle\Parser::build - Finalize the grammar rules
    • Parle\Parser::consume - Consume the data for processing
    • Parle\Parser::dump - Dump the grammar
    • Parle\Parser::errorInfo - Retrieve the error information
    • Parle\Parser::left - Declare a token with left-associativity
    • Parle\Parser::nonassoc - Declare a token with no associativity
    • Parle\Parser::precedence - Declare a precedence rule
    • Parle\Parser::push - Add a grammar rule
    • Parle\Parser::reset - Reset parser state
    • Parle\Parser::right - Declare a token with right-associativity
    • Parle\Parser::sigil - Retrieve a matching part of a rule
    • Parle\Parser::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 - Parst eine Konfigurationsdatei
    • parse_ini_string - Analysiert einen Konfigurations-String
    • parse_str - Überträgt einen String in Variablen
    • parse_url - Analysiert eine URL und gibt ihre Bestandteile zurück
    • passthru - Führt ein externes Programm aus und zeigt dessen Ausgabe an
    • password_algos - Get available password hashing algorithm IDs
    • password_get_info - Gibt Informationen über einen Hash zurück
    • password_hash - Erstellt einen Passwort-Hash
    • password_needs_rehash - Überprüft, ob der übergebene Hash mit den übergebenen Optionen übereinstimmt
    • password_verify - Überprüft, ob ein Passwort und ein Hash zusammenpassen
    • pathinfo - Liefert Informationen über einen Dateipfad
    • pclose - Schließt einen Prozess-Dateizeiger
    • pcntl_alarm - Setzt einen Zeitschalter für die Auslieferung eines Signals
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - Alias von pcntl_get_last_error
    • pcntl_exec - Führt ein angegebenes Programm im aktuellen Prozessraum aus
    • pcntl_fork - Verzweigt den laufenden Prozess
    • pcntl_getpriority - Ermittelt die Priorität eines beliebigen Prozesses
    • pcntl_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_rfork - Manipulates process resources
    • pcntl_setpriority - Ändert die Priorität eines beliebigen Prozesses
    • pcntl_signal - Richtet eine Signalverarbeitung ein
    • 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 - Wartet auf ein oder gibt den Status eines abgezweigten Kindes zurück
    • pcntl_waitpid - Wartet auf ein oder gibt den Status eines abgezweigten Kindes zurück
    • pcntl_wexitstatus - Lefert den Statuscode eines beendeten Kindes
    • pcntl_wifexited - Prüft ob der Statuscode ein erfolgreiches Beenden darstellt
    • pcntl_wifsignaled - Prüft ob der Statuscode eine Terminierung wegen eines Signals angibt
    • pcntl_wifstopped - Prüft ob der Kindprozess gerade gestoppt ist
    • pcntl_wstopsig - Gibt das Signal zurück, welches das Anhalten des Kindes verursachte
    • pcntl_wtermsig - Gibt das Signal zurück, welches das Beenden des Kindes verursachte
    • PDO::beginTransaction - Startet eine Transaktion
    • PDO::commit - Bestätigt eine Transaktion
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - Ruft den SQLSTATE-Code ab, der mit der letzten Operation über das Datenbank-Handle verknüpft ist
    • PDO::errorInfo - Ruft die erweiterten Fehlerinformationen ab, die mit der letzten Operation über das Datenbank-Handle verknüpft sind
    • PDO::exec - Führt ein SQL-Statement aus und liefert die Anzahl der betroffenen Zeilen
    • PDO::getAttribute - Ruft ein Attribut einer Datenbankverbindung ab
    • PDO::getAvailableDrivers - Liefert ein Array mit den verfügbaren PDO-Treibern
    • PDO::inTransaction - Prüft, ob es eine offene Transaktion gibt
    • PDO::lastInsertId - Liefert die ID der zuletzt eingefügten Zeile oder den Wert der zuletzt eingefügten Sequenz
    • 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 - Bereitet eine Anweisung zur Ausführung vor und liefert ein Anweisungsobjekt
    • PDO::query - Bereitet eine SQL-Anweisung ohne Platzhalter vor und führt sie aus
    • PDO::quote - Setzt eine Zeichenkette für die Verwendung in einer Abfrage in Anführungszeichen
    • PDO::rollBack - Macht eine Transaktion rückgängig (Rollback)
    • PDO::setAttribute - Setzt ein Attribut
    • PDO::sqliteCreateAggregate - Registriert eine benutzerdefinierte Aggregationsfunktion zur Verwendung in SQL-Annweisungen
    • PDO::sqliteCreateCollation - Registers a User Defined Function for use as a collating function in SQL statements
    • PDO::sqliteCreateFunction - Registriert eine benutzerdefinierte Funktion (UDF) zur Nutzung in SQL-Anweisungen
    • PDO::__construct - Erzeugt eine PDO-Instanz, die eine Datenbankverbindung darstellt
    • PDOStatement::bindColumn - Bindet eine Spalte an eine PHP-Variable
    • PDOStatement::bindParam - Bindet einen Parameter an den angegebenen Variablennamen
    • PDOStatement::bindValue - Bindet einen Wert an einen Parameter
    • PDOStatement::closeCursor - Schließt den Cursor, damit die Anweisung erneut ausgeführt werden kann
    • PDOStatement::columnCount - Liefert die Anzahl der Spalten in der Ergebnismenge
    • PDOStatement::debugDumpParams - Gibt Informationen über einen vorbereiteten SQL-Befehl aus
    • PDOStatement::errorCode - Ruft den SQLSTATE-Code ab, der mit der letzten Operation über das Anweisungs-Handle verknüpft ist
    • PDOStatement::errorInfo - Ruft die erweiterten Fehlerinformationen ab, die mit der letzten Operation über das Anweisungs-Handle verknüpft sind
    • PDOStatement::execute - Führt ein Prepared Statement aus
    • PDOStatement::fetch - Ruft die nächste Zeile aus einer Ergebnismenge ab
    • PDOStatement::fetchAll - Ruft die verbleibenden Zeilen aus einer Ergebnismenge ab
    • PDOStatement::fetchColumn - Liefert eine einzelne Spalte aus der nächsten Zeile einer Ergebnismenge
    • PDOStatement::fetchObject - Ruft die nächste Zeile ab und liefert sie als Objekt
    • PDOStatement::getAttribute - Ruft ein Attribut einer Anweisung ab
    • PDOStatement::getColumnMeta - Liefert die Metadaten zu einer Spalte einer Ergebnismenge
    • PDOStatement::getIterator - Ermittelt den Iterator der Ergebnismenge
    • PDOStatement::nextRowset - Rückt in einem Anweisungshandle mit mehreren Sätzen von Zeilen (Rowsets) zum nächsten vor
    • PDOStatement::rowCount - Liefert die Anzahl der von der letzten SQL-Anweisung betroffenen Zeilen
    • PDOStatement::setAttribute - Setzt ein Anweisungsattribut
    • PDOStatement::setFetchMode - Legt den standardmäßigen Abrufmodus eine Anweisung fest
    • 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 - Verbinden mit MySQL-Datenbanken
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLITE DSN - Verbindungen zu SQLite-Datenbanken aufbauen
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Öffnet eine persistente Verbindung zum Internet oder zu einem Unix-Domainsocket
    • pg_affected_rows - Gibt die Anzahl betroffener Datensätze (Tupel) zurück
    • pg_cancel_query - Löscht eine asynchrone Abfrage
    • pg_client_encoding - Liefert die Kodierung des Clients
    • pg_close - Schließt eine PostgreSQL-Verbindung
    • pg_connect - Öffnet eine PostgreSQL-Verbindung
    • pg_connection_busy - Gibt den Status der Verbindung zurück (busy/not busy)
    • pg_connection_reset - Setzt die Verbindung zurück und verbindet neu
    • pg_connection_status - Gibt den Verbindungsstatus zurück
    • pg_connect_poll - Poll the status of an in-progress asynchronous PostgreSQL connection attempt
    • pg_consume_input - Reads input on the connection
    • pg_convert - Konvertiert die Werte eines assoziativen Arrays in die für SQL-Anweisungen passende Form
    • pg_copy_from - Fügt Datensätze aus einem Array in eine Tabelle ein
    • pg_copy_to - Kopiert eine Tabelle in ein Array
    • pg_dbname - Liefert den Namen der Datenbank
    • pg_delete - Löscht Datensätze
    • pg_end_copy - Synchronisation mit dem PostgreSQL-Server
    • pg_escape_bytea - Maskiert Zeichenketten zum Einfügen in ein Feld vom Typ bytea
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - Maskiert einen String für Abfragen
    • pg_execute - Fordert den Datenankserver auf, eine vorbereitete Anfrage mit den angegebenen Parametern auszuführen und wartet auf das Ergebnis
    • pg_fetch_all - Liefert alle Zeilen eines Abfrageergebnisses als Array
    • pg_fetch_all_columns - Gibt alle Werte einer bestimmten Spalte eines Abfrageergebnisses in einem Array zurück
    • pg_fetch_array - Liefert eine Zeile als Array
    • pg_fetch_assoc - Liefert eine Zeile als assoziatives Array
    • pg_fetch_object - Liefert einen Datensatz als Objekt
    • pg_fetch_result - Liefert Werte aus einer Ergebnisinstanz
    • pg_fetch_row - Liefert einen Datensatz als numerisches Array
    • pg_field_is_null - Prüft, ob ein Feld einen SQL-NULL-Wert enthält
    • pg_field_name - Liefert den Namen eines Feldes
    • pg_field_num - Liefert die Feldnummer des angegebenen Feldes
    • pg_field_prtlen - Liefert die Länge des Feldes
    • pg_field_size - Liefert die interne Größe des belegten Speichers für ein Feld
    • pg_field_table - Gibt zu einem Feldnamen den Namen der Tabelle oder deren oid zurück, in der das Feld definiert ist
    • pg_field_type - Liefert den Datentyp eines Feldes
    • pg_field_type_oid - Liefert die ID des PostgreSQL-Datentyps (OID) eines Feldes
    • pg_flush - Flush outbound query data on the connection
    • pg_free_result - Gibt den durch Ergebnisse belegten Speicher frei
    • pg_get_notify - Liefert eine SQL-NOTIFY-Nachricht
    • pg_get_pid - Prüft die Datenbankverbindung
    • pg_get_result - Liefert asynchrone Abfrageergebnisse
    • pg_host - Liefert den Namen des Host, zu dem verbunden wurde
    • pg_insert - Überträgt Werte aus einem Array in eine Tabelle
    • pg_last_error - Liefert die letzte Fehlermeldung einer Verbindung
    • pg_last_notice - Liefert die letzte NOTICE-Meldung des PostgreSQL-Servers
    • pg_last_oid - Liefert den Objektbezeichner (OID) des zuletzt eingefügten Datensatzes
    • pg_lo_close - Schließt ein Large Object
    • pg_lo_create - Erzeugt ein Large Object
    • pg_lo_export - Exportiert ein Large Object in eine Datei
    • pg_lo_import - Importiert ein Large Object aus einer Datei
    • pg_lo_open - Öffnet ein Large Object
    • pg_lo_read - Liest ein Large Object
    • pg_lo_read_all - Liest ein ganzes Large Object und reicht es direkt an den Browser weiter
    • pg_lo_seek - Setzt die Lese- oder Schreibposition in einem Large Object
    • pg_lo_tell - Liefert die aktuelle Lese- oder Schreibposition in einem Large Object
    • pg_lo_truncate - Truncates a large object
    • pg_lo_unlink - Löscht ein Large Object
    • pg_lo_write - Schreibt in ein Large Object
    • pg_meta_data - Liefert die Metadaten einer Tabelle als Array
    • pg_num_fields - Gibt die Anzahl der Felder in einem Abfrageergebnis zurück
    • pg_num_rows - Gibt die Anzahl der Zeilen in einem Abfrageergebnis zurück
    • pg_options - Liefert die Verbindungsoptionen der aktuellen Verbindung
    • pg_parameter_status - Liefert den aktuellen Wert eines Parameters des Servers
    • pg_pconnect - Öffnet eine persistente PostgreSQL-Verbindung
    • pg_ping - Prüft die Datenbankverbindung
    • pg_port - Liefert die Portnummer, über die die Verbindung aufgebaut wurde
    • pg_prepare - Sendet eine Aufforderung an den Server, eine vorbereitete Anfrage mit den übergebenen Parametern zu erzeugen und wartet auf ihre Beendigung
    • pg_put_line - Sendet eine NULL-terminierte Zeichenkette zum PostgreSQL-Server
    • pg_query - Führt eine Abfrage aus
    • pg_query_params - Sendet ein Kommando zum Server und wartet seine Ausführung ab. Getrennt vom SQL-Kommando können dabei Parameter übergeben werden
    • pg_result_error - Liefert die mit der Ergebniskennung verknüpfte Fehlermeldung
    • pg_result_error_field - Liefert den Inhalt eines bestimmtes Feldes zu einer Fehlermeldung
    • pg_result_seek - Setzt den internen Datensatzzeiger auf die angegebene Position in einem Abfrageergebnis
    • pg_result_status - Liefert den Status eines Abfrageergebnisses
    • pg_select - Wählt Datensätze aus
    • pg_send_execute - Sendet eine Aufforderung an den Server, eine vorbereitete Abfrage mit den übergebenen Parametern auszuführen, ohne auf die Ergebnisse zu warten
    • pg_send_prepare - Sendet eine Aufforderung an den Server, eine vorbereitete Abfrage mit den übergebenen Parametern zu erzeugen, ohne auf ihre Beendigung zu warten
    • pg_send_query - Sendet eine asynchrone Abfrage
    • pg_send_query_params - Sendet ein Kommando und separate Parameter zum Server, ohne auf die Rückgabe der Ergebnisse zu warten
    • pg_set_client_encoding - Setzt die Kodierung des Clients
    • 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 - Bestimmt den Detaillierungsgrad von Fehlermeldungen, die von pg_last_error und pg_result_error zurückgegeben werden
    • pg_socket - Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace - Ermöglicht die Ablaufverfolgung einer Verbindung
    • pg_transaction_status - Gibt den aktuellen Transaktionsstatus des Servers zurück
    • pg_tty - Liefert den TTY-Namen für die Verbindung
    • pg_unescape_bytea - Entfernt Maskierungen für den Typ bytea
    • pg_untrace - Beendet die Ablaufverfolgung einer PostgreSQL-Verbindung
    • pg_update - Aktualisiert eine Tabelle
    • pg_version - Liefert ein Array, das die Versionen von Client, Protokoll und Server enthält (falls verfügbar).
    • phar:// - PHP Archive
    • 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
    • Phar Kontextoptionen - Liste der Phar Kontextoptionen
    • php:// - Accessing various I/O streams
    • phpcredits - Prints out the credits for PHP
    • phpdbg_break_file - Inserts a breakpoint at a line in a file
    • phpdbg_break_function - Inserts a breakpoint at entry to a function
    • phpdbg_break_method - Inserts a breakpoint at entry to a method
    • phpdbg_break_next - Inserts a breakpoint at the next opcode
    • phpdbg_clear - Clears all breakpoints
    • phpdbg_color - Sets the color of certain elements
    • phpdbg_end_oplog - Beschreibung
    • phpdbg_exec - Attempts to set the execution context
    • phpdbg_get_executable - Beschreibung
    • phpdbg_prompt - Sets the command prompt
    • phpdbg_start_oplog - Beschreibung
    • phpinfo - Liefert Informationen zur PHP-Konfiguration
    • 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 - Liefert die aktuelle PHP-Version
    • php_ini_loaded_file - Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files - Liefert eine Liste von analysierten .ini-Dateien aus einem zusätzlichen ini-Verzeichnis
    • php_sapi_name - Liefert das zwischen PHP und Webserver verwendete Interface
    • php_strip_whitespace - Return source with stripped comments and whitespace
    • php_uname - Returns information about the operating system PHP is running on
    • php_user_filter::filter - Called when applying the filter
    • php_user_filter::onClose - Called when closing the filter
    • php_user_filter::onCreate - Called when creating the filter
    • pi - Liefert den Wert von 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 - Öffnet einen Dateizeiger für einen Prozess
    • pos - Alias von current
    • posix_access - Ermittelt die Zugriffsberechtigungen einer Datei
    • posix_ctermid - Liefert den Pfad des kontrollierenden Terminals
    • posix_eaccess - Ermittelt die Zugriffsmöglichkeiten auf eine Datei
    • posix_errno - Alias von posix_get_last_error
    • posix_fpathconf - Liefert den Wert eines konfigurierbaren Limits
    • posix_getcwd - Liefert den Pfadnamen des aktuellen Verzeichnisses
    • posix_getegid - Liefert die effektive Gruppen-ID des aktuellen Prozesses
    • posix_geteuid - Liefert die effektive Benutzer-ID des aktuellen Prozesses
    • posix_getgid - Liefert die reale Gruppen-ID des aktuellen Prozesses
    • posix_getgrgid - Liefert zu einer Gruppen-ID Informationen über diese Gruppe
    • posix_getgrnam - Liefert zu einem Gruppennamen Informationen über diese Gruppe
    • posix_getgroups - Liefert die Gruppenliste des aktuellen Prozesses
    • posix_getlogin - Liefert den Loginnamen
    • posix_getpgid - Liefert die Prozessgruppenkennung (Process Group ID) für die Job-Kontrolle
    • posix_getpgrp - Liefert die Prozessgruppenkennung des aktuellen Prozesses
    • posix_getpid - Liefert die aktuelle Prozesskennung
    • posix_getppid - Liefert die Prozesskennung des Elternprozesses
    • posix_getpwnam - Liefert zu einem Benutzernamen Informationen über diesen Benutzer
    • posix_getpwuid - Liefert zu einer Benutzer-ID Informationen über diesen Benutzer
    • posix_getrlimit - Liefert Informationen über Systemressourcen-Limits
    • posix_getsid - Liefert die aktuelle Session-ID (sid) des Prozesses
    • posix_getuid - Liefert die reale Benutzer-ID des aktuellen Prozesses
    • posix_get_last_error - Liefert die von der letzten fehlgeschlagenen Posix-Funktion gesetzte Fehlernummer
    • posix_initgroups - Ermittelt die Gruppenzugriffsliste
    • posix_isatty - Ermittelt, ob ein Dateideskriptor ein interaktives Terminal ist
    • posix_kill - Sendet einem Prozess ein Signal
    • posix_mkfifo - Erzeugt eine "FIFO special"-Datei (named pipe)
    • posix_mknod - Erzeugt eine spezielle oder eine gewöhnliche Datei (POSIX.1)
    • posix_pathconf - Liefert den Wert eines konfigurierbaren Limits
    • posix_setegid - Setzt die effektive Gruppen-ID des aktuellen Prozesses
    • posix_seteuid - Setzt die effektive Benutzer-ID des aktuellen Prozesses
    • posix_setgid - Setzt die Gruppen-ID des aktuellen Prozesses
    • posix_setpgid - Setzt die Prozessgruppenkennung (Process Group ID) für die Job-Kontrolle
    • posix_setrlimit - Setzt Limits für eine Systemressource
    • posix_setsid - Macht den aktuellen Prozess zum Leiter der Session
    • posix_setuid - Setzt die Benutzer-ID des aktuellen Prozesses
    • posix_strerror - Liefert die System-Fehlermeldung, die zur angegebenen Fehlernummer gehört
    • posix_sysconf - Liefert Laufzeitinformationen des Systems
    • posix_times - Liefert Rechenzeiten
    • posix_ttyname - Ermittelt den Namen des Terminal-Devices
    • posix_uname - Liefert Auskunft über das System
    • pow - Potenzfunktion
    • preg_filter - Sucht und ersetzt mit regulären Ausdrücken
    • preg_grep - Liefert Array-Elemente, die auf ein Suchmuster passen
    • preg_last_error - Liefert den Fehlercode der letzten PCRE-RegEx-Auswertung
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - Führt eine Suche mit einem regulären Ausdruck durch
    • preg_match_all - Führt eine vollständige Suche mit einem regulären Ausdruck durch
    • preg_quote - Maskiert Zeichen regulärer Ausdrücke
    • preg_replace - Sucht und ersetzt mit regulären Ausdrücken
    • preg_replace_callback - Sucht und ersetzt mit regulären Ausdrücken unter Verwendung eines Callbacks
    • preg_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - Zerlegt eine Zeichenkette anhand eines regulären Ausdrucks
    • prev - Setzt den internen Arrayzeiger um ein Element zurück
    • print - Ausgabe eines Strings
    • printf - Liefert einen formatierten String
    • print_r - Gibt Variablen-Informationen in lesbarer Form aus
    • proc_close - Schließt einen Prozess, der mit proc_open gestartet wurde und gibt den Exitcode dieses Prozesses zurück
    • proc_get_status - Liefert Informationen über einen mit proc_open gestarteten Prozess
    • proc_nice - Ändert die Priorität des aktuellen Prozesses
    • proc_open - Führt ein Kommando aus und öffnet Dateizeiger für die Ein- und Ausgabe
    • proc_terminate - Beendet einen von proc_open gestarteten Prozess
    • property_exists - Prüft, ein Objekt oder eine Klasse auf die angegebene Eigenschaft
    • pspell_add_to_personal - Fügt der persönlichen Wortliste ein Wort hinzu
    • pspell_add_to_session - Fügt der Wortliste der aktuellen Sitzung ein Wort hinzu
    • pspell_check - Überprüft ein Wort
    • pspell_clear_session - Löscht die aktuelle Sitzung
    • pspell_config_create - Erzeugt eine Konfiguration zum Öffnen eines Wörterbuchs
    • pspell_config_data_dir - Ort der Dateien mit den Daten für die Sprachen
    • pspell_config_dict_dir - Ort der Haupt-Wortliste
    • pspell_config_ignore - Ignoriert Wörter mit weniger als N Buchstaben
    • pspell_config_mode - Ändert den Modus für die Anzahl gelieferter Vorschläge
    • pspell_config_personal - Legt die Datei fest, die die persönliche Wortliste enthält
    • pspell_config_repl - Legt die Datei fest, welche die Ersetzungspaare enthält
    • pspell_config_runtogether - Betrachtet zusammengesetzte Wörter als gültige Verbindungen
    • pspell_config_save_repl - Bestimmt, ob Ersetzungspaare zusammen mit der Wortliste gespeichert werden
    • pspell_new - Lädt ein neues Wörterbuch
    • pspell_new_config - Lädt ein neues Wörterbuch mit den Einstellungen einer angegebenen Konfiguration
    • pspell_new_personal - Lädt ein neues Wörterbuch mit persönlicher Wortliste
    • pspell_save_wordlist - Speichert die persönliche Wortliste in einer Datei
    • pspell_store_replacement - Speichert das Ersetzungspaar für ein Wort
    • pspell_suggest - Macht Vorschläge für die Schreibweise eines Wortes
    • 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 - Setzt den Wert einer Umgebungsvariablen
  • 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 - Konvertiert einen "Quoted-Printable"-String in einen 8-Bit-String
    • quoted_printable_encode - Wandelt einen 8-Bit-String in sein 'Quoted Printable' Gegenstück
    • quotemeta - Maskiert (quotet) Meta-Zeichen
  • r
    • rad2deg - Rechnet einen Winkel vom Bogenmaß in Grad um
    • 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 - Erzeugt eine zufällige Zahl
    • 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 - Erstellt ein Array mit einem Bereich von Elementen
    • 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 - Dekodiert URL-kodierte Strings
    • rawurlencode - URL-Kodierung nach RFC 3986
    • readdir - Liest einen Eintrag aus einem Verzeichnis-Handle
    • readfile - Gibt eine Datei aus
    • readgzfile - Gibt eine gz-komprimierte Datei aus
    • readline - Liest eine Zeile
    • readline_add_history - Fügt eine Zeile zur History hinzu
    • readline_callback_handler_install - Initialisiert das readline-Callback-Interface und das Terminal, gibt den Prompt aus und springt direkt zurück
    • readline_callback_handler_remove - Entfernt den letztdefinierten Callbackhandler und setzt die Terminalumgebung auf die Ursprungswerte zurück
    • readline_callback_read_char - Liest ein Zeichen und informiert das readline-Callback-Interface, wenn die Eingabezeile abgeschlossen wurde
    • readline_clear_history - Löscht die History
    • readline_completion_function - Registriert eine Vervollständigungsfunktion
    • readline_info - Liest/Setzt verschiedene interne readline-Variablen
    • readline_list_history - Auflistung der History
    • readline_on_new_line - Informiert readline, dass der Cursor in eine neue Zeile bewegt wurde
    • readline_read_history - Liest die History
    • readline_redisplay - Zeichnet den Bildschirm neu
    • readline_write_history - Schreibt die History
    • readlink - Liefert das Ziel eines symbolischen Links
    • read_exif_data - Alias von exif_read_data
    • realpath - Löst einen Pfad in einen absoluten und eindeutigen auf
    • realpath_cache_get - Get realpath cache entries
    • realpath_cache_size - Get realpath cache size
    • recode - Alias von recode_string
    • recode_file - Umkodierung von Dateien entsprechend der Recode-Anweisung
    • recode_string - Kodiert einen String entsprechend einer Recode-Anweisung um
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object
    • RecursiveCachingIterator::getChildren - Return the inner iterator's children as a RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Check whether the current element of the inner iterator has children
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Returns an iterator for the current entry if it is a directory
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Returns whether current entry is a directory and not '.' or '..'
    • RecursiveDirectoryIterator::key - Return path and filename of current dir entry
    • RecursiveDirectoryIterator::next - Zum nächsten Eintrag bewegen
    • RecursiveDirectoryIterator::rewind - Rewind dir back to the start
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry
    • RecursiveIterator::hasChildren - Returns if an iterator can be created for the current entry
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Access the current element value
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Get the current depth of the recursive iteration
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - The current active sub iterator
    • RecursiveIteratorIterator::key - Access the current key
    • RecursiveIteratorIterator::next - Move forward to the next element
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Rewind the iterator to the first element of the top level inner iterator
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPostfix - Set postfix
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Exports
    • Reflection::getModifierNames - 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 - Alias von 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 - Print extension info
    • 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 - Get the name of the type as a 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 - Registriert eine Funktion zur Ausführung beim Skript-Abschluss
    • register_tick_function - Register a function for execution on each tick
    • rename - Benennt eine Datei oder ein Verzeichnis um
    • reset - Setzt den internen Zeiger eines Arrays auf sein erstes Element
    • ResourceBundle::count - Get number of elements in the bundle
    • ResourceBundle::create - Create a resource bundle
    • ResourceBundle::get - Get data from the bundle
    • ResourceBundle::getErrorCode - Get bundle's last error code
    • ResourceBundle::getErrorMessage - Get bundle's last error message
    • ResourceBundle::getLocales - Get supported locales
    • restore_error_handler - Stellt die zuvor benutzte Fehlerbehandlungsfunktion wieder her
    • restore_exception_handler - Stellt den vorherigen Exceptionhandler wieder her
    • restore_include_path - Restores the value of the include_path configuration option
    • Result::getAffectedItemsCount - Ermittelt die Anzahl der betroffenen Zeilen
    • Result::getAutoIncrementValue - Ruft einen automatisch erhöhten Wert ab
    • Result::getGeneratedIds - Ruft die zuletzt erzeugten IDs ab
    • Result::getWarnings - Ruft die Warnungen der letzten Operation ab
    • Result::getWarningsCount - Ermittelt die Anzahl der Warnungen der letzten Operation
    • Result::__construct - Der Konstruktor der Klasse Result
    • ReturnTypeWillChange::__construct - Erstellt eine neue Instanz des Attributs ReturnTypeWillChange
    • rewind - Setzt die Position eines Dateizeigers auf den Anfang
    • rewinddir - Setzt das Verzeichnis-Handle an den Anfang zurück
    • rmdir - Löscht ein Verzeichnis
    • 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 - Rundet einen Gleitkommawert
    • RowResult::fetchAll - Ruft alle Zeilen aus einer Ergebnismenge ab
    • RowResult::fetchOne - Ruft eine Zeile aus einer Ergebnismenge ab
    • RowResult::getColumnNames - Ruft alle Spaltennamen aus einer Ergebnismenge ab
    • RowResult::getColumns - Ruft die Metadaten der Spalten aus einer Ergebnismenge ab
    • RowResult::getColumnsCount - Ermittelt die Anzahl der Spalten einer Ergebnismenge
    • RowResult::getWarnings - Ruft die Warnungen der letzten Operation ab
    • RowResult::getWarningsCount - Ermittelt die Anzahl der Warnungen der letzten Operation
    • RowResult::__construct - Der Konstruktor der Klasse RowResult
    • 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 - Sortiert ein Array in absteigender Reihenfolge
    • rtrim - Entfernt Leerraum (oder andere Zeichen) vom Ende eines Strings
    • 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 - Listet Dateien und Verzeichnisse innerhalb eines angegebenen Pfades auf
    • Schema::createCollection - Fügt einem Schema eine Sammlung hinzu
    • Schema::dropCollection - Entfernt eine Sammlung aus einem Schema
    • Schema::existsInDatabase - Prüft, ob es das angegebene Objekt in der Datenbank gibt
    • Schema::getCollection - Ruft eine Sammlung aus einem Schema ab
    • Schema::getCollectionAsTable - Ruft eine Sammlung als Table-Objekt ab
    • Schema::getCollections - Ruft alle Sammlungen eines Schemas ab
    • Schema::getName - Ruft den Namen eines Schemas ab
    • Schema::getSession - Ruft eine Schema-Session ab
    • Schema::getTable - Ruft eine Tabelle eines Schemas ab
    • Schema::getTables - Ruft alle Tabellen eines Schemas ab
    • Schema::__construct - Der Konstruktor der Klasse Schema
    • SchemaObject::getSchema - Ruft ein Schema-Objekt ab
    • 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 - Fordert Zugriff auf einen Semaphor an
    • sem_get - Fordert Zugriff auf eine Semaphor-ID an
    • sem_release - Gibt einen Semaphor frei
    • sem_remove - Entfernt einen Semaphor
    • SensitiveParameter::__construct - Erstellt eine neue Instanz des Attributs SensitiveParameter
    • SensitiveParameterValue::getValue - Liefert einen sensiblen Wert
    • SensitiveParameterValue::__construct - Erstellt ein neues SensitiveParameterValue-Objekt
    • SensitiveParameterValue::__debugInfo - Schützt einen sensiblen Wert vor versehentlicher Offenlegung
    • Serializable::serialize - Die String-Darstellung eines Objekts
    • Serializable::unserialize - Erstellt das Objekt
    • serialize - Erzeugt eine speicherbare Repräsentation eines Wertes
    • Session::close - Schließt eine Session
    • Session::createSchema - Erstellt ein neues Schema
    • Session::dropSchema - Löscht ein Schema
    • Session::generateUUID - Erzeugt eine neue UUID
    • Session::getDefaultSchema - Ruft den Namen des Standardschemas ab
    • Session::getSchema - Ruft ein neues Schema-Objekt ab
    • Session::getSchemas - Ruft Schema-Objekte ab
    • Session::getServerVersion - Ruft die Serverversion ab
    • Session::listClients - Ruft eine Liste der Clients ab
    • Session::quoteName - Fügt Anführungszeichen hinzu
    • Session::releaseSavepoint - Entfernt einen gesetzten Sicherungspunkt
    • Session::rollback - Macht eine Transaktion rückgängig (Rollback)
    • Session::rollbackTo - Macht eine Transaktion bis zu einem Sicherungspunkt rückgängig
    • Session::setSavepoint - Erzeugt einen Sicherungspunkt
    • Session::sql - Erzeugt eine SQL-Anweisung
    • Session::startTransaction - Startet eine Transaktion
    • Session::__construct - Der Konstruktor der Klasse Session
    • SessionHandler::close - Schließt eine Session
    • SessionHandler::create_sid - Liefert eine neue Session-ID
    • SessionHandler::destroy - Löscht eine Session
    • SessionHandler::gc - Löscht alte Sessions
    • SessionHandler::open - Initialisiert eine Session
    • SessionHandler::read - Ruft die Session-Daten ab
    • SessionHandler::write - Speichert die Session-Daten
    • SessionHandlerInterface::close - Schließt eine Session
    • SessionHandlerInterface::destroy - Löscht eine Session
    • SessionHandlerInterface::gc - Löscht alte Sessions
    • SessionHandlerInterface::open - Initialisiert eine Session
    • SessionHandlerInterface::read - Ruft die Session-Daten ab
    • SessionHandlerInterface::write - Speichert die Session-Daten
    • SessionIdInterface::create_sid - Erzeugt eine Session-ID
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Aktualisiert den Zeitstempel
    • SessionUpdateTimestampHandlerInterface::validateId - Validiert eine ID
    • session_abort - Verwirft Änderungen am Session-Array und beendet die Session
    • session_cache_expire - Liefert und/oder setzt die aktuelle Cache-Verfallszeit
    • session_cache_limiter - Liefert und/oder setzt die aktuelle Cacheverwaltung
    • session_commit - Alias von session_write_close
    • session_create_id - Erzeugt eine neue Session-ID
    • session_decode - Dekodiert die Daten einer Session aus einer session-kodierten Zeichenkette
    • session_destroy - Löscht alle in einer Session registrierten Daten
    • session_encode - Kodiert die Daten der aktuellen Session als session-kodierte Zeichenkette
    • session_gc - Führt die Garbage Collection der Session-Daten durch
    • session_get_cookie_params - Liefert die Parameter des Session-Cookies
    • session_id - Liefert und/oder setzt die aktuelle Session-ID
    • session_module_name - Liefert und/oder setzt das aktuelle Session-Modul
    • session_name - Liefert und/oder setzt den Namen der aktuellen Session
    • session_regenerate_id - Ersetzt die aktuelle Session-ID durch eine neu erzeugte
    • session_register_shutdown - Funktion zum Schließen von Sessions
    • session_reset - Initialisiert das Session-Array mit seinen ursprünglichen Werten neu
    • session_save_path - Liefert und/oder setzt den aktuellen Speicherpfad der Session
    • session_set_cookie_params - Setzt die Session-Cookie-Parameter
    • session_set_save_handler - Setzt benutzerdefinierte Session-Speicherfunktionen
    • session_start - Erzeugt eine neue Session oder setzt eine vorhandene fort
    • session_status - Liefert den Status der aktuellen Session
    • session_unset - Löscht alle Session-Variablen
    • session_write_close - Speichert die Session-Daten und beendet die Session
    • setcookie - Sendet ein Cookie
    • setlocale - Legt regionale (locale) Einstellungen fest
    • setrawcookie - Sendet ein Cookie, ohne seinen Wert zu URL-kodieren
    • settype - Legt den Typ einer Variablen fest
    • set_error_handler - Bestimmt eine benutzerdefinierte Funktion zur Fehlerbehandlung
    • set_exception_handler - Installiert einen benutzerdefinierten Exceptionhandler
    • set_file_buffer - Alias von stream_set_write_buffer
    • set_include_path - Setzt die Konfigurationsoption include_path
    • set_time_limit - Beschränkt die maximale Ausführungszeit
    • sha1 - Berechnet den SHA1-Hash eines Strings
    • sha1_file - Berechnet den SHA1-Hash einer Datei
    • shell_exec - Führt einen Befehl auf der Shell aus und liefert die komplette Ausgabe als String
    • shmop_close - Schließt einen gemeinsamen Speicherbereich
    • shmop_delete - Löscht einen gemeinsamen Speicherbereich
    • shmop_open - Erstellt oder öffnet einen gemeinsamen Speicherbereich
    • shmop_read - Liest Daten aus einem gemeinsamen Speicherbereich
    • shmop_size - Gibt die Größe des gemeinsamen Speicherbereichs zurück
    • shmop_write - Schreibt Daten in einen gemeinsamen Speicherbereich
    • shm_attach - Erzeugt oder öffnet einen gemeinsamen Speicherbereich
    • shm_detach - Beendet die Anbindung an einen gemeinsamen Speicherbereich
    • shm_get_var - Liest eine Variable aus dem gemeinsamen Speicherbereich
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Erstellt oder aktualisiert eine Variable im gemeinsamen Speicherbereich
    • shm_remove - Entfernt einen gemeinsamen Speicherbereich unter UNIX
    • shm_remove_var - Entfernt eine Variable aus dem gemeinsamen Speicherbereich
    • show_source - Alias von highlight_file
    • shuffle - Mischt die Elemente eines Arrays
    • 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 - Berechnet die Ähnlichkeit zweier Zeichenketten
    • SimpleXMLElement::addAttribute - Fügt einem SimpleXML-Element ein Attribut hinzu
    • SimpleXMLElement::addChild - Fügt dem XML-Knoten ein Kind-Element hinzu
    • SimpleXMLElement::asXML - Liefert einen wohlgeformten XML-String, der auf einem SimpleXML-Element basiert
    • SimpleXMLElement::attributes - Liefert die Attribute eines Elements
    • SimpleXMLElement::children - Findet Kindelemente des gegebenen Knotens
    • SimpleXMLElement::count - Counts the children of an element
    • SimpleXMLElement::current - Returns the current element
    • SimpleXMLElement::getChildren - Returns the sub-elements of the current element
    • SimpleXMLElement::getDocNamespaces - Liefert die im Dokument deklarierten Namensräume
    • SimpleXMLElement::getName - Ermittelt den Namen eines XML-Elements
    • SimpleXMLElement::getNamespaces - Gibt die im Dokument verwendeten Namespaces zurück
    • SimpleXMLElement::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLElement::key - Return current key
    • SimpleXMLElement::next - Move to next element
    • SimpleXMLElement::registerXPathNamespace - Erzeugt einen Prefix/Namespace-Kontext für den nächsten XPath-Query
    • SimpleXMLElement::rewind - Rewind to the first element
    • SimpleXMLElement::saveXML - Alias von SimpleXMLElement::asXML
    • SimpleXMLElement::valid - Check whether the current element is valid
    • SimpleXMLElement::xpath - Führt eine XPath-Anfrage auf XML-Daten aus
    • SimpleXMLElement::__construct - Erstellt ein neues SimpleXMLElement-Objekt
    • SimpleXMLElement::__toString - Returns the string content
    • simplexml_import_dom - Erzeugt ein SimpleXMLElement-Objekt aus einem DOM-Knoten
    • simplexml_load_file - Übersetzt eine XML-Datei in ein Objekt
    • simplexml_load_string - Übersetzt einen XML-String in ein Objekt
    • sin - Sinus
    • sinh - Sinus hyperbolikus
    • sizeof - Alias von count
    • sleep - Verzögert die Programmausführung
    • 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 - Ruft ein SNMP-Objekt ab
    • 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 - Setzt den Wert eines SNMP-Objekts
    • snmpwalk - Ruft alle SNMP-Objekte eines Agenten ab
    • snmpwalkoid - Ruft den Informationsbaum einer Netzwerkeinheit ab
    • snmp_get_quick_print - Holt den aktuellen Wert der quick_print-Einstellung der NET-SNMP-Bibliothek
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Alias von snmp_set_oid_output_format
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Setzt den Wert von enable innerhalb der NET-SNMP-Bibliothek
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::__call - Ruft eine SOAP-Funktion auf (veraltet)
    • SoapClient::__construct - SoapClient-Konstruktor
    • SoapClient::__doRequest - Führt eine SOAP-Anfrage aus
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Liefert eine Liste verfügbarer SOAP-Funktionen
    • SoapClient::__getLastRequest - Gibt die letzte SOAP-Anfrage zurück
    • SoapClient::__getLastRequestHeaders - Gibt die SOAP-Header der letzten Anfrage zurück
    • SoapClient::__getLastResponse - Gibt die letzte SOAP-Antwort zurück
    • SoapClient::__getLastResponseHeaders - Gibt die SOAP-Header der letzten Antwort zurück
    • SoapClient::__getTypes - Gibt eine Liste der SOAP-Typen zurück
    • SoapClient::__setCookie - Definiert ein Cookie für Soap-Anfragen
    • SoapClient::__setLocation - Bestimmt die Adresse des zu nutzenden Webservices
    • SoapClient::__setSoapHeaders - Setzt die SOAP-Header für nachfolgende Aufrufe
    • SoapClient::__soapCall - Ruft eine SOAP-Funktion auf
    • SoapFault::__construct - SoapFault-Konstruktor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::__construct - SoapHeader-Konstruktor
    • SoapParam::__construct - SoapParam-Konstruktor
    • SoapServer->setPersistence() - Versetzt einen SoapServer in den Persistenz-Modus
    • SoapServer::addFunction - Fügt eine oder mehrere Funktionen zur Verarbeitung von SOAP-Anfragen hinzu
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Erzeugt einen SoapServer-Fehler, der einen Fehlerzustand anzeigt
    • SoapServer::getFunctions - Gibt eine Liste aller definierten Funktionen zurück
    • SoapServer::handle - Verarbeitet eine SOAP-Anfrage
    • SoapServer::setClass - Setzt die Klasse, welche SOAP-Anfragen verarbeitet
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::__construct - SoapServer-Konstruktor
    • SoapVar::__construct - SoapVar-Konstruktor
    • Socket-Kontextoptionen - Liste der Socket-Kontextoptionen
    • socket_accept - Akzeptiert eine Verbindung an einem Socket
    • socket_addrinfo_bind - Create and bind to a socket from a given addrinfo
    • socket_addrinfo_connect - Create and connect to a socket from a given addrinfo
    • socket_addrinfo_explain - Get information about addrinfo
    • socket_addrinfo_lookup - Get array with contents of getaddrinfo about the given hostname
    • socket_atmark - Determines whether socket is at out-of-band mark
    • socket_bind - Verknüpft einen Socket mit einem Namen
    • socket_clear_error - Löscht entweder einen Fehler oder den letzten Fehlercode eines Sockets
    • socket_close - Schließt eine Socket-Instanz
    • socket_cmsg_space - Calculate message buffer size
    • socket_connect - Baut eine Verbindung über einen Socket auf
    • socket_create - Erzeugt einen Socket (Endpunkt für die Kommunikation)
    • socket_create_listen - Öffnet einen Socket, um Verbindungen über einem gegebenen Port aufzubauen
    • socket_create_pair - Erzeugt ein Paar nicht zu unterscheidender Sockets und speichert sie in einem Array
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - Alias von socket_get_option
    • socket_getpeername - Fragt das entfernte Ende eines gegebenen Sockets ab. Das Ergebnis ist vom Typ abhängig und ist entweder das Paar host/port oder ein Pfad des Unix-Dateisystems
    • socket_getsockname - Fragt das lokale Ende eines gegebenen Sockets ab. Das Ergebnis ist vom Typ abhängig und ist entweder das Paar host/port oder ein Pfad des Unix-Dateisystems
    • socket_get_option - Liefert die Socket-Optionen für einen Socket
    • socket_get_status - Alias von stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Gibt den letzten Fehler zurück, der an einem Socket aufgetreten ist
    • socket_listen - Hört einen Socket nach Verbindungsanforderungen ab
    • socket_read - Liest höchstens die angegebene Anzahl Bytes von einem Socket
    • socket_recv - Empfängt Daten von einem verbundenen Socket
    • socket_recvfrom - Empfängt Daten von einem Socket, egal, ob verbindungsorientiert oder nicht
    • socket_recvmsg - Read a message
    • socket_select - Führt einen select()-Systemaufruf auf den gegebenen Socket-Arrays aus, wobei ein Zeitlimit bestimmt wird
    • socket_send - Sendet Daten an einen verbundenen Socket
    • socket_sendmsg - Send a message
    • socket_sendto - Sendet eine Nachricht an einen Socket, egal ob dieser verbunden ist oder nicht
    • socket_setopt - Alias von socket_set_option
    • socket_set_block - Setzt einen Socket auf den blockieren-Modus
    • socket_set_blocking - Alias von stream_set_blocking
    • socket_set_nonblock - Setzt den nonblocking-Modus für den Dateideskriptor fd
    • socket_set_option - Setzt die Optionen für einen Socket
    • socket_set_timeout - Alias von stream_set_timeout
    • socket_shutdown - Schließt einen Socket der zum Senden, Empfangen oder beidem geöffnet wurde
    • socket_strerror - Gibt einen String zurück, der einen Socket-Fehler beschreibt
    • socket_write - Schreibt in einen 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 - Addition großer Zahlen
    • sodium_base642bin - Dekodiert eine Base64-kodierte Zeichenkette in das Binärformat.
    • sodium_bin2base64 - Kodiert eine binäre Zeichenkette mit Base64.
    • sodium_bin2hex - Kodiert in Hexadezimal
    • sodium_compare - Vergleicht große Zahlen
    • sodium_crypto_aead_aes256gcm_decrypt - Überprüft und entschlüsselt eine Nachricht mit AES-256-GCM
    • sodium_crypto_aead_aes256gcm_encrypt - Verschlüsselt und authentifiziert eine Nachricht mit AES-256-GCM
    • sodium_crypto_aead_aes256gcm_is_available - Prüft, ob die Hardware AES256-GCM unterstützt
    • sodium_crypto_aead_aes256gcm_keygen - Generiert einen zufälligen AES-256-GCM-Schlüssel
    • sodium_crypto_aead_chacha20poly1305_decrypt - Überprüft und entschlüsselt eine Nachricht mit ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_encrypt - Verschlüsselt und authentifiziert eine Nachricht mit ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt - Überprüft, ob der Chiffriertext ein gültiges Tag enthält
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt - Verschlüsselt eine Nachricht
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen - Generiert einen zufälligen ChaCha20-Poly1305-IETF-Schlüssel.
    • sodium_crypto_aead_chacha20poly1305_keygen - Generiert einen zufälligen ChaCha20-Poly1305-Schlüssel
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - (Empfohlen) Überprüft und entschlüsselt eine Nachricht mit XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - (Empfohlen) Verschlüsselt und authentifiziert eine Nachricht mit XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Generiert einen zufälligen XChaCha20-Poly1305-Schlüssel.
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Generate a random key for sodium_crypto_auth
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Authenticated public-key encryption
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Create a unified keypair string from a secret key and public key
    • sodium_crypto_box_open - Authenticated public-key decryption
    • sodium_crypto_box_publickey - Extract the public key from a crypto_box keypair
    • sodium_crypto_box_publickey_from_secretkey - Calculate the public key from a secret key
    • sodium_crypto_box_seal - Anonymous public-key encryption
    • sodium_crypto_box_seal_open - Anonymous public-key decryption
    • sodium_crypto_box_secretkey - Extracts the secret key from a crypto_box keypair
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_core_ristretto255_add - Adds an element
    • sodium_crypto_core_ristretto255_from_hash - Maps a vector
    • sodium_crypto_core_ristretto255_is_valid_point - Determines if a point on the ristretto255 curve
    • sodium_crypto_core_ristretto255_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_add - Adds a scalar value
    • sodium_crypto_core_ristretto255_scalar_complement - The sodium_crypto_core_ristretto255_scalar_complement purpose
    • sodium_crypto_core_ristretto255_scalar_invert - Inverts a scalar value
    • sodium_crypto_core_ristretto255_scalar_mul - Multiplies a scalar value
    • sodium_crypto_core_ristretto255_scalar_negate - Negates a scalar value
    • sodium_crypto_core_ristretto255_scalar_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_reduce - Reduces a scalar value
    • sodium_crypto_core_ristretto255_scalar_sub - Subtracts a scalar value
    • sodium_crypto_core_ristretto255_sub - Subtracts an element
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash for streaming
    • sodium_crypto_generichash_keygen - Generate a random generichash key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Generate a random root key for the KDF interface
    • sodium_crypto_kx_client_session_keys - Calculate the client-side session keys.
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Extract the public key from a crypto_kx keypair
    • sodium_crypto_kx_secretkey - Extract the secret key from a crypto_kx keypair.
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Calculate the server-side session keys.
    • sodium_crypto_pwhash - Derive a key from a password, using Argon2
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password, using scrypt
    • sodium_crypto_pwhash_scryptsalsa208sha256_str - Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify - Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_str - Get an ASCII-encoded hash
    • sodium_crypto_pwhash_str_needs_rehash - Determine whether or not to rehash a password
    • sodium_crypto_pwhash_str_verify - Verifies that a password matches a hash
    • sodium_crypto_scalarmult - Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_scalarmult_base - Alias von 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 - Dekodiert eine hexadezimal kodierte binäre Zeichenkette
    • sodium_increment - Inkrementieren einer großen Zahl
    • sodium_memcmp - Prüfung auf Gleichheit bei konstanter Zeit
    • sodium_memzero - Überschreibt eine Zeichenkette mit einem Nullzeichen
    • sodium_pad - Fügt Fülldaten hinzu
    • sodium_unpad - Entfernt Fülldaten
    • 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 - Alias von 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 - Alias von 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 - Alias von SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - Alias von 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 - Alias von SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addGroupField - Add a field to be used to group results
    • SolrQuery::addGroupFunction - Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery - Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField - Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::collapse - Collapses the result set to a single document per group
    • SolrQuery::getExpand - Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries - Returns the expand filter queries
    • SolrQuery::getExpandQuery - Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows - Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields - Returns an array of fields
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getGroup - Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent - Returns group cache percent value
    • SolrQuery::getGroupFacet - Returns the group.facet parameter value
    • SolrQuery::getGroupFields - Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat - Returns the group.format value
    • SolrQuery::getGroupFunctions - Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit - Returns the group.limit value
    • SolrQuery::getGroupMain - Returns the group.main value
    • SolrQuery::getGroupNGroups - Returns the group.ngroups value
    • SolrQuery::getGroupOffset - Returns the group.offset value
    • SolrQuery::getGroupQueries - Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields - Returns the group.sort value
    • SolrQuery::getGroupTruncate - Returns the group.truncate value
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExpand - Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery - Sets the expand.q parameter
    • SolrQuery::setExpandRows - Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setGroup - Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent - Enables caching for result grouping
    • SolrQuery::setGroupFacet - Sets group.facet parameter
    • SolrQuery::setGroupFormat - Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit - Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups - If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset - Sets the group.offset parameter
    • SolrQuery::setGroupTruncate - If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrServerException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - Returns the current version of the Apache Solr extension
    • sort - Sortiert ein Array in aufsteigender Reihenfolge
    • soundex - Berechnet die Laut-Ähnlichkeit eines Strings
    • 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 - Alias von 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 - Try all registered __autoload() functions to load the requested class
    • spl_autoload_extensions - Registriert und gibt die voreingestellten Dateiendungen für spl_autoload zurück
    • spl_autoload_functions - Liefert alle registrierten __autoload()-Funktionen
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - Return available SPL classes
    • 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 - Gibt einen formatierten String zurück
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Gibt die Anzahl der Datenbankreihen zurück, die durch die letzte SQL-Anfrage verändert, gelöscht oder hinzugefügt wurden.
    • SQLite3::close - Beendet eine Datenbankverbindung
    • SQLite3::createAggregate - Registriert eine PHP-Funktion zum Gebrauch als SQL-Aggregat-Funktion
    • SQLite3::createCollation - Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction - Registriert eine PHP-Funktion, die als SQL-Skalar-Funktion genutzt werden kann
    • SQLite3::enableExceptions - Enable throwing exceptions
    • SQLite3::escapeString - Gibt eine passend maskierte Zeichenkette zurück
    • SQLite3::exec - Führt eine ergebnislose Abfrage an eine Datenbank aus
    • SQLite3::lastErrorCode - Gibt den numerischen Ergebniscode der letzten fehlgeschlagenen SQLite-Anweisung zurück
    • SQLite3::lastErrorMsg - Gibt einen englischen Text zurück, der die letzten fehlgeschlagenen SQLite-Anfrage beschreibt.
    • SQLite3::lastInsertRowID - Gibt die Datensatz-Id des zuletzt getätigten INSERT in die Datenbank zurück
    • SQLite3::loadExtension - Versucht eine SQLite-Erweiterungsbibliothek zu laden
    • SQLite3::open - Öffnet eine SQlite-Datenbank
    • SQLite3::openBlob - Opens a stream resource to read a BLOB
    • SQLite3::prepare - Bereitet eine SQL-Anweisung für die Ausführung vor
    • SQLite3::query - Führt eine SQL-Anfrage aus
    • 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 - Instanziiert ein SQLite3-Objekt und öffnet eine SQLite3-Datenbank
    • 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 - Bindet die Parameter einer Anweisung
    • SqlStatement::execute - Führt eine Operation aus
    • SqlStatement::getNextResult - Ruft das nächste Ergebnis ab
    • SqlStatement::getResult - Ruft ein Ergebnis ab
    • SqlStatement::hasMoreResults - Prüft, ob es weitere Ergebnisse gibt
    • SqlStatement::__construct - Der Konstruktor der Klasse SqlStatement
    • SqlStatementResult::fetchAll - Ruft alle Zeilen aus dem Ergebnis ab
    • SqlStatementResult::fetchOne - Ruft eine Zeile aus dem Ergebnis ab
    • SqlStatementResult::getAffectedItemsCount - Ermittelt die Anzahl der betroffenen Zeilen
    • SqlStatementResult::getColumnNames - Ruft die Namen der Spalten ab
    • SqlStatementResult::getColumns - Ruft Spalten ab
    • SqlStatementResult::getColumnsCount - Ermittelt die Anzahl der Spalten
    • SqlStatementResult::getGeneratedIds - Ruft die zuletzt erzeugten IDs ab
    • SqlStatementResult::getLastInsertId - Ruft die ID der letzten Einfügung ab
    • SqlStatementResult::getWarnings - Ruft die Warnungen der letzten Operation ab
    • SqlStatementResult::getWarningsCount - Ermittelt die Anzahl der Warnungen der letzten Operation
    • SqlStatementResult::hasData - Prüft, ob die Ergebnismenge Daten enthält
    • SqlStatementResult::nextResult - Ruft das nächste Ergebnis ab
    • SqlStatementResult::__construct - Der Konstruktor der Klasse SqlStatementResult
    • sqrt - Quadratwurzel
    • srand - Legt den Anfangswert für den Zufallsgenerator fest
    • sscanf - Überträgt einen String in ein angegebenes Format
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_agent - Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_disconnect - Close a connection to a remote SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_forward_accept - Accept a connection created by a listener
    • ssh2_forward_listen - Bind a port on the remote server and listen for connections
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_poll - Poll the channels/listeners/streams for events
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_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
    • SSL-Kontext-Optionen - Liste der SSL-Kontext-Optionen
    • stat - Sammelt Informationen über eine Datei
    • Statement::getNextResult - Ruft das nächste Ergebnis ab
    • Statement::getResult - Ruft ein Ergebnis ab
    • Statement::hasMoreResults - Prüft, ob es weitere Ergebnisse gibt
    • Statement::__construct - Der Konstruktor der Klasse Statement
    • 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 - Vergleich von Zeichenketten ohne Unterscheidung der Groß- und Kleinschreibung (binärsicher)
    • strchr - Alias von strstr
    • strcmp - Vergleich zweier Strings (binärsicher)
    • strcoll - Locale-basierter Zeichenkettenvergleich
    • strcspn - Ermittelt die Anzahl der nicht übereinstimmenden Zeichen
    • streamWrapper::dir_closedir - Close directory handle
    • streamWrapper::dir_opendir - Open directory handle
    • streamWrapper::dir_readdir - Read entry from directory handle
    • streamWrapper::dir_rewinddir - Rewind directory handle
    • streamWrapper::mkdir - Create a directory
    • streamWrapper::rename - Renames a file or directory
    • streamWrapper::rmdir - Removes a directory
    • streamWrapper::stream_cast - Retrieve the underlaying resource
    • streamWrapper::stream_close - Close a resource
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Flushes the output
    • streamWrapper::stream_lock - Advisory file locking
    • streamWrapper::stream_metadata - Change stream metadata
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Read from stream
    • streamWrapper::stream_seek - Seeks to specific location in a stream
    • streamWrapper::stream_set_option - Change stream options
    • streamWrapper::stream_stat - Retrieve information about a file resource
    • streamWrapper::stream_tell - Retrieve the current position of a stream
    • streamWrapper::stream_truncate - Truncate stream
    • streamWrapper::stream_write - Write to stream
    • streamWrapper::unlink - Delete a file
    • streamWrapper::url_stat - Retrieve information about a file
    • streamWrapper::__construct - Constructs a new stream wrapper
    • streamWrapper::__destruct - Destructs an existing stream wrapper
    • stream_bucket_append - Append bucket to brigade
    • stream_bucket_make_writeable - Returns a bucket object from the brigade to operate on
    • stream_bucket_new - Create a new bucket for use on the current stream
    • stream_bucket_prepend - Prepend bucket to brigade
    • stream_context_create - Creates a stream context
    • stream_context_get_default - Retrieve the default stream context
    • stream_context_get_options - Retrieve options for a stream/wrapper/context
    • stream_context_get_params - Retrieves parameters from a context
    • stream_context_set_default - Set the default stream context
    • stream_context_set_option - Sets an option for a stream/wrapper/context
    • stream_context_set_options - Sets options on the specified context
    • stream_context_set_params - Set parameters for a stream/wrapper/context
    • stream_copy_to_stream - Copies data from one stream to another
    • stream_filter_append - Attach a filter to a stream
    • stream_filter_prepend - Attach a filter to a stream
    • stream_filter_register - Register a user defined stream filter
    • stream_filter_remove - Remove a filter from a stream
    • stream_get_contents - Reads remainder of a stream into a string
    • stream_get_filters - Retrieve list of registered filters
    • stream_get_line - Gets line from stream resource up to a given delimiter
    • stream_get_meta_data - Retrieves header/meta data from streams/file pointers
    • stream_get_transports - Retrieve list of registered socket transports
    • stream_get_wrappers - Retrieve list of registered streams
    • stream_isatty - Check if a stream is a TTY
    • stream_is_local - Checks if a stream is a local stream
    • stream_notification_callback - A callback function for the notification context parameter
    • stream_register_wrapper - Alias von stream_wrapper_register
    • stream_resolve_include_path - Resolve filename against the include path
    • stream_select - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
    • stream_set_blocking - Set blocking/non-blocking mode on a stream
    • stream_set_chunk_size - Set the stream chunk size
    • stream_set_read_buffer - Set read file buffering on the given stream
    • stream_set_timeout - Set timeout period on a stream
    • stream_set_write_buffer - Sets write file buffering on the given stream
    • stream_socket_accept - Accept a connection on a socket created by stream_socket_server
    • stream_socket_client - Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto - Turns encryption on/off on an already connected socket
    • stream_socket_get_name - Retrieve the name of the local or remote sockets
    • stream_socket_pair - Creates a pair of connected, indistinguishable socket streams
    • stream_socket_recvfrom - Receives data from a socket, connected or not
    • stream_socket_sendto - Sends a message to a socket, whether it is connected or not
    • stream_socket_server - Create an Internet or Unix domain server socket
    • stream_socket_shutdown - Shutdown a full-duplex connection
    • stream_supports_lock - Tells whether the stream supports locking
    • stream_wrapper_register - Register a URL wrapper implemented as a PHP class
    • stream_wrapper_restore - Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister - Unregister a URL wrapper
    • strftime - Formatiert eine Zeit-/Datumsangabe gemäß dem Gebietsschema
    • Stringable::__toString - Liefert die String-Darstellung eines Objekts
    • stripcslashes - Demaskiert einen mit addcslashes maskierten String
    • stripos - Findet das erste Vorkommen eines Teilstrings in einem String, unabhängig von Groß- und Kleinschreibung
    • stripslashes - Entfernt Maskierungszeichen aus einem String
    • strip_tags - Entfernt HTML- und PHP-Tags aus einem String
    • stristr - Wie strstr, aber unabhängig von Groß- bzw. Kleinschreibung
    • strlen - Ermitteln der String-Länge
    • strnatcasecmp - String-Vergleich "natürlicher Ordnung" ohne Berücksichtigung der Groß- und Kleinschreibung
    • strnatcmp - String-Vergleich unter Verwendung einer "natürlichen Ordnung"
    • strncasecmp - Binärsicherer Vergleich von Zeichenketten der ersten n Zeichen ohne Berücksichtigung der Groß- und Kleinschreibung
    • strncmp - String-Vergleich der ersten n Zeichen (binärsicher)
    • strpbrk - Durchsucht einen String nach einem Zeichen aus einer Gruppe von Zeichen
    • strpos - Sucht die Position des ersten Vorkommens des Suchstrings in einem String
    • strptime - Wertet eine Zeit-/Datumsangabe aus, die mit strftime erzeugt wurde
    • strrchr - Sucht das letzte Vorkommen eines Zeichens in einem String
    • strrev - Kehrt einen String um
    • strripos - Findet das letzte Vorkommen der gesuchten Zeichenkette in einem String, unabhängig von Groß- und Kleinschreibung
    • strrpos - Findet die Position des letzten Vorkommens eines Teilstrings innerhalb einer Zeichenkette
    • strspn - Ermittelt die Länge des initialen Abschnitts einer Zeichenkette, der ausschließlich aus Zeichen besteht, die in einer übergebenen Maske enthalten sind
    • strstr - Findet das erste Vorkommen eines Strings
    • strtok - Zerlegt einen String
    • strtolower - Setzt einen String in Kleinbuchstaben um
    • strtotime - Wandelt eine textuelle englische Datums- und Zeitbeschreibung in einen Unix-Zeitstempel um
    • strtoupper - Wandelt alle Zeichen eines Strings in Großbuchstaben um
    • strtr - Tauscht Zeichen aus oder ersetzt Zeichenketten
    • strval - Ermittelt die String-Repräsentation einer Variable
    • str_contains - Determine if a string contains a given substring
    • str_decrement - Decrement an alphanumeric string
    • str_ends_with - Checks if a string ends with a given substring
    • str_getcsv - Parst einen CSV-String in ein Array
    • str_increment - Increment an alphanumeric string
    • str_ireplace - Groß- und kleinschreibungsunabhängige Version von str_replace
    • str_pad - Erweitert einen String unter Verwendung eines anderen Strings auf eine bestimmte Länge
    • str_repeat - Wiederholt einen String
    • str_replace - Ersetzt alle Vorkommen des Suchstrings durch einen anderen String
    • str_rot13 - Führt die ROT13-Transformation auf einen String aus
    • str_shuffle - Mischt einen String nach dem Zufallsprinzip
    • str_split - Konvertiert einen String in ein Array
    • str_starts_with - Checks if a string starts with a given substring
    • str_word_count - Liefert Informationen über in einem String verwendete Worte
    • substr - Liefert einen Teil eines Strings
    • substr_compare - Binärsicherer Vergleich zweier Strings, beginnend an einer bestimmten Position und endend nach einer festgelegten Länge
    • substr_count - Ermittelt, wie oft eine Zeichenkette in einem String vorkommt
    • substr_replace - Ersetzt Text innerhalb einer Zeichenkette
    • 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 parameters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start - Start the swoole http server.
    • Swoole\Lock::lock - Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::lock_read - Lock a read-write lock for reading.
    • Swoole\Lock::trylock - Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::trylock_read - Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::unlock - Release the lock.
    • Swoole\Lock::__construct - Construct a memory lock.
    • Swoole\Lock::__destruct - Destory a Swoole memory lock.
    • Swoole\Mmap::open - Map a file into memory and return the stream resource which can be used by PHP stream operations.
    • Swoole\MySQL::close - Close the async MySQL connection.
    • Swoole\MySQL::connect - Connect to the remote MySQL server.
    • Swoole\MySQL::getBuffer - Description
    • Swoole\MySQL::on - Register callback function based on event name.
    • Swoole\MySQL::query - Run the SQL query.
    • Swoole\MySQL::__construct - Construct an async MySQL client.
    • Swoole\MySQL::__destruct - Destory the async MySQL client.
    • Swoole\Process::alarm - High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close - Close the pipe to the child process.
    • Swoole\Process::daemon - Change the process to be a daemon process.
    • Swoole\Process::exec - Execute system commands.
    • Swoole\Process::exit - Stop the child processes.
    • Swoole\Process::freeQueue - Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill - Send signal to the child process.
    • Swoole\Process::name - Set name of the process.
    • Swoole\Process::pop - Read and pop data from the message queue.
    • Swoole\Process::push - Write and push data into the message queue.
    • Swoole\Process::read - Read data sending to the process.
    • Swoole\Process::signal - Send signal to the child processes.
    • Swoole\Process::start - Start the process.
    • Swoole\Process::statQueue - Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue - Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait - Wait for the events of child processes.
    • Swoole\Process::write - Write data into the pipe and communicate with the parent process or child processes.
    • Swoole\Process::__construct - Construct a process.
    • Swoole\Process::__destruct - Destroy 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 destroy a timer.
    • Swoole\Server::close - Close a connection to the client.
    • Swoole\Server::confirm - Check status of the connection.
    • Swoole\Server::connection_info - Get the connection info by file description.
    • Swoole\Server::connection_list - Get all of the established connections.
    • Swoole\Server::defer - Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server::exist - Check if the connection is existed.
    • Swoole\Server::finish - Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo - Get the connection info by file description.
    • Swoole\Server::getClientList - Get all of the established connections.
    • Swoole\Server::getLastError - Get the error code of the most recent error.
    • Swoole\Server::heartbeat - Check all the connections on the server.
    • Swoole\Server::listen - Listen on the given IP and port, socket type.
    • Swoole\Server::on - Register a callback function by event name.
    • Swoole\Server::pause - Stop receiving data from the connection.
    • Swoole\Server::protect - Set the connection to be protected mode.
    • Swoole\Server::reload - Restart all the worker process.
    • Swoole\Server::resume - Start receving data from the connection.
    • Swoole\Server::send - Send data to the client.
    • Swoole\Server::sendfile - Send file to the connection.
    • Swoole\Server::sendMessage - Send message to worker processes by ID.
    • Swoole\Server::sendto - Send data to the remote UDP address.
    • Swoole\Server::sendwait - Send data to the remote socket in the blocking way.
    • Swoole\Server::set - Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown - Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start - Start the Swoole server.
    • Swoole\Server::stats - Get the stats of the Swoole server.
    • Swoole\Server::stop - Stop the Swoole server.
    • Swoole\Server::task - Send data to the task worker processes.
    • Swoole\Server::taskwait - Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti - Execute multiple tasks concurrently.
    • Swoole\Server::tick - Repeats a given function at every given time-interval.
    • Swoole\Server::__construct - Construct a Swoole server.
    • Swoole\Server\Port::on - Register callback functions by event.
    • Swoole\Server\Port::set - Set protocol of the server port.
    • Swoole\Server\Port::__construct - Construct a server port
    • Swoole\Server\Port::__destruct - Destory server port
    • Swoole\Table::column - Set the data type and size of the columns.
    • Swoole\Table::count - Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create - Create the swoole memory table.
    • Swoole\Table::current - Get the current row.
    • Swoole\Table::decr - Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del - Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy - Destroy the Swoole table.
    • Swoole\Table::exist - Check if a row is existed by $row_key.
    • Swoole\Table::get - Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr - Increment the value by $row_key and $column_key.
    • Swoole\Table::key - Get the key of current row.
    • Swoole\Table::next - Iterator the next row.
    • Swoole\Table::rewind - Rewind the iterator.
    • Swoole\Table::set - Update a row of the table by $row_key.
    • Swoole\Table::valid - Check 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 - Erzeugt einen symbolischen Link
    • 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 - Erzeugt eine Meldung für das System-Log
    • system - Führt ein externes Programm aus und zeigt dessen Ausgabe an
    • sys_getloadavg - Ermittelt die durchschnittliche Systemlast
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • Table::count - Ermittelt die Anzahl der Zeilen
    • Table::delete - Löscht Zeilen aus einer Tabelle
    • Table::existsInDatabase - Prüft, ob es die angegebene Tabelle in der Datenbank gibt
    • Table::getName - Ruft den Namen einer Tabelle ab
    • Table::getSchema - Ruft das Schema einer Tabelle ab
    • Table::getSession - Ruft die Session zu einer Tabelle ab
    • Table::insert - Fügt Zeilen in eine Tabelle ein
    • Table::isView - Prüft, ob eine Tabelle ein View ist
    • Table::select - Wählt Zeilen aus einer Tabelle aus
    • Table::update - Aktualisiert Zeilen in einer Tabelle
    • Table::__construct - Der Konstruktor der Klasse Table
    • TableDelete::bind - Bindet die Parameter für eine DELETE-Anweisung
    • TableDelete::execute - Führt eine DELETE-Anweisung aus
    • TableDelete::limit - Begrenzt die Anzahl der zu löschenden Zeilen
    • TableDelete::orderby - Setzt die Sortierkriterien für eine DELETE-Anweisung
    • TableDelete::where - Setzt die Suchbedingung für eine DELETE-Anweisung
    • TableDelete::__construct - Der Konstruktor der Klasse TableDelete
    • TableInsert::execute - Führt eine INSERT-Anweisung aus
    • TableInsert::values - Fügt Werte für eine einzufügende Zeile hinzu
    • TableInsert::__construct - Der Konstruktor der Klasse TableInsert
    • TableSelect::bind - Bindet die Parameter für eine SELECT-Anweisung
    • TableSelect::execute - Führt eine SELECT-Anweisung aus
    • TableSelect::groupBy - Setzt die Gruppierungskriterien für eine SELECT-Anweisung
    • TableSelect::having - Setzt die HAVING-Bedingung für eine SELECT-Anweisung
    • TableSelect::limit - Begrenzt die Anzahl der zurückgegebenen Dokumente
    • TableSelect::lockExclusive - Führt eine Operation mit EXCLUSIVE LOCK aus
    • TableSelect::lockShared - Führt eine Operation mit SHARED LOCK aus
    • TableSelect::offset - Setzt die Anzahl der zu überspringenden Zeilen
    • TableSelect::orderby - Setzt die Sortierkriterien für eine SELECT-Anweisung
    • TableSelect::where - Setzt die Suchbedingung für eine SELECT-Anweisung
    • TableSelect::__construct - Der Konstruktor der Klasse TableSelect
    • TableUpdate::bind - Bindet die Parameter für eine UPDATE-Anweisung
    • TableUpdate::execute - Führt eine UPDATE-Anweisung aus
    • TableUpdate::limit - Begrenzt die Anzahl der zu aktualisierenden Zeilen
    • TableUpdate::orderby - Setzt die Sortierkriterien für eine UPDATE-Anweisung
    • TableUpdate::set - Fügt eine zu aktualisierende Spalte hinzu
    • TableUpdate::where - Setzt den Suchfilter
    • TableUpdate::__construct - Der Konstruktor der Klasse TableUpdate
    • taint - Taint a string
    • tan - Tangens
    • tanh - Tangens hyperbolikus
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Erzeugt eine Datei mit eindeutigem Dateinamen
    • textdomain - Setzt die Standarddomain
    • 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 - Liefert den Exception-Code
    • Throwable::getFile - Liefert die Datei, in der das Objekt erzeugt wurde
    • Throwable::getLine - Liefert die Zeile, in der das Objekt instantiiert wurde
    • Throwable::getMessage - Liefert die Nachricht
    • Throwable::getPrevious - Liefert das vorherige Throwable
    • Throwable::getTrace - Liefert den Stacktrace
    • Throwable::getTraceAsString - Liefert den Stacktrace als String
    • Throwable::__toString - Gibt eine Repräsentation des geworfenen Objekts als String zurück
    • 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 - Liefert den aktuellen Unix-Zeitstempel
    • timezone_abbreviations_list - Alias von DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Alias von DateTimeZone::listIdentifiers
    • timezone_location_get - Alias von DateTimeZone::getLocation
    • timezone_name_from_abbr - Liefert den Namen einer Zeitzone, ausgehend von der Abkürzung und der UTC-Abweichung
    • timezone_name_get - Alias von DateTimeZone::getName
    • timezone_offset_get - Alias von DateTimeZone::getOffset
    • timezone_open - Alias von DateTimeZone::__construct
    • timezone_transitions_get - Alias von DateTimeZone::getTransitions
    • timezone_version_get - Liefert die Version der timezonedb
    • time_nanosleep - Verzögert die Ausführung um die gegebene Anzahl Sekunden und Nanosekunden
    • time_sleep_until - Lässt das Skript bis zur angegebenen Zeit schlafen
    • tmpfile - Erstellt eine temporäre Datei
    • token_get_all - Spaltet angegebenen PHP-Quelltext in PHP-Token auf
    • token_name - Gibt Bezeichner für ein PHP-Token zurück
    • touch - Setzt die Zugriffs- und Modifikationszeit einer Datei
    • 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 - Prüft, ob der Trait existiert
    • 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 - Erzeugt eine benutzerdefinierte Fehlermeldung/Warnung/Benachrichtigung
    • trim - Entfernt Whitespaces (oder andere Zeichen) am Anfang und Ende eines Strings
  • u
    • uasort - Sortiert ein Array mittels einer benutzerdefinierten Vergleichsfunktion und behält Index-Assoziationen bei
    • ucfirst - Verwandelt das erste Zeichen eines Strings in einen Großbuchstaben
    • UConverter::convert - Convert string from one charset to another
    • UConverter::fromUCallback - Default "from" callback function
    • UConverter::getAliases - Get the aliases of the given name
    • UConverter::getAvailable - Get the available canonical converter names
    • UConverter::getDestinationEncoding - Get the destination encoding
    • UConverter::getDestinationType - Get the destination converter type
    • UConverter::getErrorCode - Get last error code on the object
    • UConverter::getErrorMessage - Get last error message on the object
    • UConverter::getSourceEncoding - Get the source encoding
    • UConverter::getSourceType - Get the source converter type
    • UConverter::getStandards - Get standards associated to converter names
    • UConverter::getSubstChars - Get substitution chars
    • UConverter::reasonText - Get string representation of the callback reason
    • UConverter::setDestinationEncoding - Set the destination encoding
    • UConverter::setSourceEncoding - Set the source encoding
    • UConverter::setSubstChars - Set the substitution chars
    • UConverter::toUCallback - Default "to" callback function
    • UConverter::transcode - Convert a string from one character encoding to another
    • UConverter::__construct - Create UConverter object
    • ucwords - Wandelt jeden ersten Buchstaben eines Wortes innerhalb eines Strings in einen Großbuchstaben um
    • 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 - Sortiert ein Array nach Schlüsseln mittels einer benutzerdefinierten Vergleichsfunktion
    • umask - Changes the current umask
    • uniqid - Erzeugt eine eindeutige ID
    • UnitEnum::cases - Liefert eine Liste der Fälle einer Enum
    • unixtojd - Konvertiert Unix-Timestamp in Julianisches Datum
    • unlink - Löscht eine Datei
    • unpack - Entpackt die Daten einer binäre Zeichenkette
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - Erzeugt aus einem gespeicherten Datenformat einen Wert in PHP
    • unset - Löschen einer angegebenen Variablen
    • 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 - Dekodiert eine URL-kodierte Zeichenkette
    • urlencode - URL-kodiert einen String
    • user_error - Alias von trigger_error
    • use_soap_error_handler - Definiert, ob der SOAP-Errorhandler benutzt werden soll
    • usleep - Verzögert die Programmausführung (in Mikrosekunden)
    • usort - Sortiert ein Array nach Werten mittels einer benutzerdefinierten Vergleichsfunktion
    • utf8_decode - Konvertiert eine Zeichenkette von UTF-8 nach ISO-8859-1 und ersetzt ungültige und nicht darstellbare Zeichen
    • utf8_encode - Konvertiert eine Zeichenkette von ISO-8859-1 nach UTF-8
  • v
    • V8Js::executeString - Führt JavaScript-Code aus
    • V8Js::getExtensions - Gibt ein Array der registrierten Erweiterungen zurück
    • V8Js::getPendingException - Liefert eine ausstehende ungefangene JavaScript-Exception
    • V8Js::registerExtension - Registriert JavaScript-Erweiterungen für V8Js
    • V8Js::__construct - Erstellt ein neues V8Js-Objekt
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant::__construct - Der variant-Klassenkonstruktor
    • 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 - Gibt alle Informationen zu einer Variablen aus
    • var_export - Liefert den Inhalt einer Variablen als parsbaren PHP-Code
    • var_representation - Returns a short, readable, parsable string representation of a variable
    • version_compare - Vergleicht zwei Versionsnummer-Zeichenketten im PHP-Versionsformat
    • vfprintf - Schreibt einen formatierten String in einen Stream
    • virtual - Führt eine Apache-Unteranfrage durch
    • vprintf - Gibt einen formatierten String aus
    • vsprintf - Gibt einen formatierten String zurück
    • 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 - Der Konstruktor der Klasse Warning
    • wddx_add_vars - Fügt dem WDDX-Paket mit der übergebenen ID Werte hinzu
    • wddx_deserialize - Deserialisiert ein WDDX Paket
    • wddx_packet_end - Schließt das WDDX-Paket mit der angegebenen ID
    • wddx_packet_start - Beginnt ein neues WDDX-Paket mit einer Struktur
    • wddx_serialize_value - Serialisiert einen einzelnen Wert in ein WDDX-Paket
    • wddx_serialize_vars - Serialisiert Variablen in ein WDDX-Paket
    • WeakMap::count - Zählt die aktiven Einträge in der Map
    • WeakMap::getIterator - Liefert einen externen Iterator
    • WeakMap::offsetExists - Prüft, ob ein bestimmtes Objekt in der Map enthalten ist
    • WeakMap::offsetGet - Gibt den Wert zurück, der einem bestimmten Objekt zugeordnet ist
    • WeakMap::offsetSet - Aktualisiert die Map mit einem neuen Schlüssel-Wert-Paar
    • WeakMap::offsetUnset - Entfernt einen Eintrag aus der Map
    • WeakReference::create - Erzeugt eine neue schwache Referenz
    • WeakReference::get - Ruft ein schwach referenziertes Objekt ab
    • WeakReference::__construct - Konstruktor, der Instanziierung verhindert
    • 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 - Umbricht einen String nach einer bestimmten Anzahl Zeichen
    • 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 - Alias von xdiff_file_bdiff
    • xdiff_file_merge3 - Merge 3 files into one
    • xdiff_file_patch - Patch a file with an unified diff
    • xdiff_file_patch_binary - Alias von xdiff_file_bpatch
    • xdiff_file_rabdiff - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff - Make binary diff of two strings
    • xdiff_string_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_string_bpatch - Patch a string with a binary diff
    • xdiff_string_diff - Make unified diff of two strings
    • xdiff_string_diff_binary - Alias von xdiff_string_bdiff
    • xdiff_string_merge3 - Merge 3 strings into one
    • xdiff_string_patch - Patch a string with an unified diff
    • xdiff_string_patch_binary - Alias von 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->moveToElement - Zeiger positionieren auf das Elternelement des aktuellen Attributes
    • XMLReader::close - Beendet die XMLReader-Eingabe
    • XMLReader::expand - Gibt eine Kopie des aktuellen Knotens als DOM-Objekt zurück
    • XMLReader::getAttribute - Liefert den Wert eines Attributes nach Namen
    • XMLReader::getAttributeNo - Gibt den Wert eines Attributes nach Position zurück
    • XMLReader::getAttributeNs - Gibt den Wert eines Attributes nach lokalem Namen und URI zurück
    • XMLReader::getParserProperty - Zeigt an, ob die angegebene Eigenschaft gesetzt wurde
    • XMLReader::isValid - Zeigt an, ob das geparste Dokument valide ist
    • XMLReader::lookupNamespace - Prüft, ob ein Namensbereich für einen Präfix vorhanden ist
    • XMLReader::moveToAttribute - Zeiger auf benanntes Attribut setzen
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToFirstAttribute - Zeiger auf erstes Attribut setzen
    • XMLReader::moveToNextAttribute - Zeiger auf nächstes Attribut setzen
    • XMLReader::next - Zeiger auf nächstes Element setzen und Kinder überspringen
    • XMLReader::open - URI angeben, die auf XML-Inhalt verweist, der geparst werden soll
    • XMLReader::read - Zeiger auf das nächste Element setzen
    • XMLReader::readInnerXml - Erhalte XML des aktuellen Knotens
    • XMLReader::readOuterXml - Liest XML des aktuellen Knotens, inklusive den Knoten selbst
    • XMLReader::readString - Liest den Inhalt des aktuellen Knotens als Zeichenkette
    • XMLReader::setParserProperty - Parser-Optionen setzen
    • XMLReader::setRelaxNGSchema - Dateiname oder URI des RelaxNG-Schema setzen
    • XMLReader::setRelaxNGSchemaSource - Zeichenkette setzen, die RelaxNG-Schemadaten enthält
    • XMLReader::setSchema - Validiert Dokument gegen XSD
    • XMLReader::XML - Zeichenkette setzen, deren Inhalt geparst werden soll
    • xmlrpc_decode - Decodes XML into native PHP types
    • xmlrpc_decode_request - Decodes XML into native PHP types
    • xmlrpc_encode - Generates XML for a PHP value
    • xmlrpc_encode_request - Generates XML for a method request
    • xmlrpc_get_type - Gets xmlrpc type for a PHP value
    • xmlrpc_is_fault - Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions - Decodes XML into a list of method descriptions
    • xmlrpc_server_add_introspection_data - Adds introspection documentation
    • xmlrpc_server_call_method - Parses XML requests and call methods
    • xmlrpc_server_create - Creates an xmlrpc server
    • xmlrpc_server_destroy - Destroys server resources
    • xmlrpc_server_register_introspection_callback - Register a PHP function to generate documentation
    • xmlrpc_server_register_method - Register a PHP function to resource method matching method_name
    • xmlrpc_set_type - Sets xmlrpc type, base64 or datetime, for a PHP string value
    • XMLWriter::endAttribute - Attribute beenden
    • XMLWriter::endCdata - Beendet CDATA-Block
    • XMLWriter::endComment - Beendet Kommentar
    • XMLWriter::endDocument - Beendet Dokument
    • XMLWriter::endDtd - Beendet DTD
    • XMLWriter::endDtdAttlist - Beendet DTD-Attributliste
    • XMLWriter::endDtdElement - Beendet DTD-Element
    • XMLWriter::endDtdEntity - Beendet DTD-Entität
    • XMLWriter::endElement - Beendet Element
    • XMLWriter::endPi - Beendet Verarbeitungsvorschrift
    • XMLWriter::flush - Puffer schreiben
    • XMLWriter::fullEndElement - Beendet Element
    • XMLWriter::openMemory - Erzeugt einen neuen XMLWriter, der Stringausgaben in den Speicher schreibt
    • XMLWriter::openUri - Erzeugt neuen XMLWriter, der URI für Ausgabe verwendet
    • XMLWriter::outputMemory - Gibt Puffer zurück
    • XMLWriter::setIndent - Einrückung ein-/ausschalten
    • XMLWriter::setIndentString - Setzt Zeichenkette, die zur Einrückung verwendet wird
    • XMLWriter::startAttribute - Attribut beginnen
    • XMLWriter::startAttributeNs - Namensraum-Attribut beginnen
    • XMLWriter::startCdata - CDATA-Block beginnen
    • XMLWriter::startComment - Kommentar beginnen
    • XMLWriter::startDocument - Dokument beginnen
    • XMLWriter::startDtd - DTD beginnen
    • XMLWriter::startDtdAttlist - DTD-Attributliste beginnen
    • XMLWriter::startDtdElement - DTD-Element beginnen
    • XMLWriter::startDtdEntity - DTD-Entität beginnen
    • XMLWriter::startElement - Element beginnen
    • XMLWriter::startElementNs - Element mit Namensraum beginnen
    • XMLWriter::startPi - Verarbeitungsvorschrift beginnen
    • XMLWriter::text - Text schreiben
    • XMLWriter::writeAttribute - Komplettes Attribut schreiben
    • XMLWriter::writeAttributeNs - Komplettes Attribute mit Namensraum schreiben
    • XMLWriter::writeCdata - Kompletten CDATA-Block schreiben
    • XMLWriter::writeComment - Kompletten Kommentar schreiben
    • XMLWriter::writeDtd - Komplettes DTD-Tag schreiben
    • XMLWriter::writeDtdAttlist - Komplette DTD-Attributliste schreiben
    • XMLWriter::writeDtdElement - Komplettes DTD-Element schreiben
    • XMLWriter::writeDtdEntity - Komplette DTD-Entität schreiben
    • XMLWriter::writeElement - Komplettes Element schreiben
    • XMLWriter::writeElementNs - Komplettes Element mit Namensraum schreiben
    • XMLWriter::writePi - Komplette Verarbeitungsvorschrift-Tag schreiben
    • XMLWriter::writeRaw - Reines XML schreiben
    • xml_error_string - Get XML parser error string
    • 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 - Get XML parser error code
    • xml_parse - Start parsing an XML document
    • xml_parser_create - Create an XML parser
    • xml_parser_create_ns - Create an XML parser with namespace support
    • xml_parser_free - Free an XML parser
    • xml_parser_get_option - Get options from an XML parser
    • xml_parser_set_option - Set options in an XML parser
    • xml_parse_into_struct - Parse XML data into an array structure
    • 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 - Liefert den Wert eines Parameters
    • XSLTProcessor::getSecurityPrefs - Liefert die Sicherheitseinstellungen
    • XSLTProcessor::hasExsltSupport - Prüft, ob die EXSLT-Unterstützung aktiviert ist
    • XSLTProcessor::importStylesheet - Importiert ein Stylesheet
    • XSLTProcessor::registerPHPFunctions - Aktiviert die Nutzbarkeit von PHP-Funktionen als XSLT-Funktionen
    • XSLTProcessor::removeParameter - Löscht einen Parameter
    • XSLTProcessor::setParameter - Setzt den Wert für einen Parameter
    • XSLTProcessor::setProfiling - Setzt den Dateinamen für die Ausgaben des Profilers
    • XSLTProcessor::setSecurityPrefs - Setzt die Sicherheitseinstellungen
    • XSLTProcessor::transformToDoc - Transformiert in ein Dokument
    • XSLTProcessor::transformToUri - Transformiert in einen URI
    • XSLTProcessor::transformToXml - Transformiert in einen XML-String
    • XSLTProcessor::__construct - Erzeugt ein neues XSLTProcessor-Objekt
  • 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 - Liefert eine eindeutige ID für den aktuellen Thread
    • zend_version - Liefert die aktuelle Version der Zend-Engine
    • Zip-Kontextoptionen - Liste der Zip-Kontextoptionen
    • ZipArchive::addEmptyDir - Fügt ein neues Verzeichnis hinzu
    • ZipArchive::addFile - Fügt eine Datei von einem gegebenen Pfad zu einem ZIP-Archiv hinzu
    • ZipArchive::addFromString - Fügt eine Datei unter Verwendung ihres Inhalts zu einem ZIP-Archiv hinzu
    • 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 - Schließt das aktive Archiv (geöffnet oder neu erstellt)
    • ZipArchive::count - Counts the number of files in the archive
    • ZipArchive::deleteIndex - Löscht einen Archiveintrag unter Verwendung seines Index
    • ZipArchive::deleteName - Löscht einen Archiveintrag unter Verwendung seines Namens
    • ZipArchive::extractTo - Extrahiert den Archivinhalt
    • ZipArchive::getArchiveComment - Gibt den ZIP-Archiv-Kommentar zurück
    • ZipArchive::getArchiveFlag - Returns the value of a Zip archive global flag
    • ZipArchive::getCommentIndex - Gibt den Kommentar zu einem Eintrag unter Verwendung des Eintragsindex zurück
    • ZipArchive::getCommentName - Gibt den Kommentar zu einem Eintrag unter Verwendung des Eintragsnamens zurück
    • 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 - Gibt den Inhalt eines Eintrags unter Verwendung seines Index zurück
    • ZipArchive::getFromName - Gibt den Inhalt eines Eintrags unter Verwendung seines Namens zurück
    • ZipArchive::getNameIndex - Gibt den Namen eines Eintrags unter Verwendung seines Index zurück
    • ZipArchive::getStatusString - Gibt die Statusfehlermeldung sowie System- oder ZIP-Meldungen zurück
    • ZipArchive::getStream - Erzeugt einen Dateizeiger zu dem per Name bestimmten Eintrag (nur lesend)
    • 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 - Gibt den Index eines Archiveintrags zurück
    • ZipArchive::open - Öffnet ein ZIP-Dateiarchiv
    • ZipArchive::registerCancelCallback - Register a callback to allow cancellation during archive close.
    • ZipArchive::registerProgressCallback - Register a callback to provide updates during archive close.
    • ZipArchive::renameIndex - Benennt einen durch seinen Index bestimmten Eintrag um
    • ZipArchive::renameName - Benennt einen durch seinen Namen bestimmten Eintrag um
    • ZipArchive::replaceFile - Replace file in ZIP archive with a given path
    • ZipArchive::setArchiveComment - Setzt einen Kommentar zu einem ZIP-Archiv
    • ZipArchive::setArchiveFlag - Set a global flag of a ZIP archive
    • ZipArchive::setCommentIndex - Setzt einen Eintragskommentar, der via Eintragsindex bestimmt wird
    • ZipArchive::setCommentName - Setzt einen Eintragskommentar, der via Eintragsnamen bestimmt wird
    • 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 - Gibt die Details eines via Index bestimmten Eintrags zurück
    • ZipArchive::statName - Gibt die Details eines via Namen bestimmten Eintrags zurück
    • ZipArchive::unchangeAll - Setzt alle im Archiv durchgeführten Änderungen zurück
    • ZipArchive::unchangeArchive - Nimmt alle globalen Änderungen zurück, die im Archiv durchgeführt wurden
    • ZipArchive::unchangeIndex - Nimmt alle Änderungen zurück, die auf dem Eintrag mit dem gegebenen Index gemacht wurden
    • ZipArchive::unchangeName - Nimmt alle Änderungen zurück, die auf dem Eintrag mit dem gegebenen Namen gemacht wurden
    • zip_close - Schließt ein ZIP-Archiv
    • zip_entry_close - Schließt einen Verzeichniseintrag
    • zip_entry_compressedsize - Ermittelt die komprimierte Größe eines Verzeichniseintrages
    • zip_entry_compressionmethod - Ermittelt die Komprimierungsmethode eines Verzeichniseintrags
    • zip_entry_filesize - Ermittelt die effektive Größe eines Verzeichniseintrages
    • zip_entry_name - Gibt den Namen eines Verzeichniseintrages zurück
    • zip_entry_open - Öffnet einen Verzeichniseintrag für den Lesezugriff
    • zip_entry_read - Liest einen geöffneten Verzeichniseintrag aus
    • zip_open - Öffnet ein ZIP-Archiv
    • zip_read - Liest den nächsten Eintrag innerhalb des ZIP-Archivs
    • Zlib-Kontextoptionen - Liste der Zlib-Kontextoptionen
    • zlib:// - Compression Streams
    • zlib_decode - Dekomprimiert raw-/gzip-/zlib-kodierte Daten
    • zlib_encode - Komprimiert Daten mit der gewählten Kodierung
    • zlib_get_coding_type - Gibt die für Ausgabekomprimierung genutzte Methode zurück
    • ZMQ::__construct - ZMQ constructor
    • ZMQContext::getOpt - Get context option
    • ZMQContext::getSocket - Create a new socket
    • ZMQContext::isPersistent - Whether the context is persistent
    • ZMQContext::setOpt - Set a socket option
    • ZMQContext::__construct - Construct a new ZMQContext object
    • ZMQDevice::getIdleTimeout - Get the idle timeout
    • ZMQDevice::getTimerTimeout - Get the timer timeout
    • ZMQDevice::run - Run the new device
    • ZMQDevice::setIdleCallback - Set the idle callback function
    • ZMQDevice::setIdleTimeout - Set the idle timeout
    • ZMQDevice::setTimerCallback - Set the timer callback function
    • ZMQDevice::setTimerTimeout - Set the timer timeout
    • ZMQDevice::__construct - Construct a new device
    • ZMQPoll::add - Add item to the poll set
    • ZMQPoll::clear - Clear the poll set
    • ZMQPoll::count - Count items in the poll set
    • ZMQPoll::getLastErrors - Get poll errors
    • ZMQPoll::poll - Poll the items
    • ZMQPoll::remove - Remove item from poll set
    • ZMQSocket::bind - Bind the socket
    • ZMQSocket::connect - Connect the socket
    • ZMQSocket::disconnect - Disconnect a socket
    • ZMQSocket::getEndpoints - Get list of endpoints
    • ZMQSocket::getPersistentId - Get the persistent id
    • ZMQSocket::getSocketType - Get the socket type
    • ZMQSocket::getSockOpt - Get socket option
    • ZMQSocket::isPersistent - Whether the socket is persistent
    • ZMQSocket::recv - Receives a message
    • ZMQSocket::recvMulti - Receives a multipart message
    • ZMQSocket::send - Sends a message
    • ZMQSocket::sendmulti - Sends a multipart message
    • ZMQSocket::setSockOpt - Set a socket option
    • ZMQSocket::unbind - Unbind the socket
    • ZMQSocket::__construct - Construct a new ZMQSocket
    • Zookeeper::addAuth - Specify application credentials
    • Zookeeper::close - Close the zookeeper handle and free up any resources
    • Zookeeper::connect - Create a handle to used communicate with zookeeper
    • Zookeeper::create - Create a node synchronously
    • Zookeeper::delete - Delete a node in zookeeper synchronously
    • Zookeeper::exists - Checks the existence of a node in zookeeper synchronously
    • Zookeeper::get - Gets the data associated with a node synchronously
    • Zookeeper::getAcl - Gets the acl associated with a node synchronously
    • Zookeeper::getChildren - Lists the children of a node synchronously
    • Zookeeper::getClientId - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getConfig - Get instance of ZookeeperConfig
    • Zookeeper::getRecvTimeout - Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
    • Zookeeper::getState - Get the state of the zookeeper connection
    • Zookeeper::isRecoverable - Checks if the current zookeeper connection state can be recovered
    • Zookeeper::set - Sets the data associated with a node
    • Zookeeper::setAcl - Sets the acl associated with a node synchronously
    • Zookeeper::setDebugLevel - Sets the debugging level for the library
    • Zookeeper::setDeterministicConnOrder - Enable/disable quorum endpoint order randomization
    • Zookeeper::setLogStream - Sets the stream to be used by the library for logging
    • Zookeeper::setWatcher - Set a watcher function
    • Zookeeper::__construct - Create a handle to used communicate with zookeeper
    • ZookeeperConfig::add - Add servers to the ensemble
    • ZookeeperConfig::get - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
    • ZookeeperConfig::remove - Remove servers from the ensemble
    • ZookeeperConfig::set - Change ZK cluster ensemble membership and roles of ensemble peers
    • zookeeper_dispatch - Calls callbacks for pending operations
  • _
    • __autoload - Versucht, eine undefinierte Klasse zu laden
    • __halt_compiler - Beendet die Kompilerausführung

User Contributed Notes

There are no user contributed notes for this page.


Verzeichnis der Beispiele

Verzeichnis aller Beispiele im Handbuch

  • Example#0 - Ein einführendes Beispiel
  • Example#1 - Unser erstes PHP-Skript: hallo.php
  • Example#2 - Anzeigen von Systeminformationen mit PHP
  • Example#3 - Variable ausgeben (Array-Element)
  • Example#4 - Beispiel, das Kontrollstrukturen und Funktionen verwendet
  • Example#5 - HTML- und PHP-Modus vermischt
  • Example#6 - Ein einfaches HTML-Formular
  • Example#7 - Daten des Formulars ausgeben
  • Example#8 - Ein Teil der lighttpd.conf
  • Example#9 - FastCGI-Responder erzeugen
  • Example#10 - Mit entfernten FCGI-Instanzen verbinden
  • Example#11 - Beispiel für die Installation von OpenBSD-Paketen
  • Example#12 - Beispiel einer Debian-Installation mit Apache 2
  • Example#13 - Stoppen und Starten von Apache nach der Installation von PHP
  • Example#14 - Methoden zur Anzeige weiterer PHP-Pakete
  • Example#15 - PHP mit MySQL und cURL installieren
  • Example#16 - Empfohlene Konfiguration für OpCache
  • Example#17 - Empfohlene Konfiguration für WinCache
  • Example#18 - Kommandozeilen-Konfiguration von IIS und PHP
  • Example#19 - Änderungen in der Registry
  • Example#20 - PHP und Apache 2.x als Handler
  • Example#21 - PHP und Apache 2.x als CGI
  • Example#22 - Apache für die Ausführung von PHP als FastCGI konfigurieren
  • Example#23 - Übergabe von Umgebungsvariablen und PHP-Einstellungen an einen Pool
  • Example#24 - Festlegen von PHP-Einstellungen in nginx.conf
  • Example#25 - Aufruf der Funktion phpinfo
  • Example#26 - php.ini Umgebungsvariablen
  • Example#27 - php.ini-Beispiel
  • Example#28 - Apache-Konfigurationsbeispiel
  • Example#29 - Öffnende und schließende PHP-Tags
  • Example#30 - Fortgeschrittene Ausgabe unter Verwendung von Bedingungen
  • Example#31 - Beispiel für den schließenden Tag, der den abschließenden Zeilenumbruch einschließt
  • Example#32 - Integer literals
  • Example#33 - Integer overflow on a 32-bit system
  • Example#34 - Integer overflow on a 64-bit system
  • Example#35 - Grundlegendes Heredoc-Beispiel ab PHP 7.3.0
  • Example#36 - Der schließende Bezeichner darf nicht weiter eingerückt sein, als die Zeilen des Textkörpers
  • Example#37 - Unterschiedliche Einrückung für den Bezeichner, der den Textkörper (Leerzeichen) schließt
  • Example#38 - Fortsetzen eines Ausdrucks nach einem schließenden Bezeichner
  • Example#39 - Ein schließender Bezeichner im Textkörper der Zeichenkette führt zu einem ParseError
  • Example#40 - Ungültiges Beispiel vor PHP 7.3.0
  • Example#41 - Gültiges Beispiel, auch vor PHP 7.3.0
  • Example#42 - Beispiel für das Notieren von Heredoc-Strings
  • Example#43 - Beispiel für Heredoc in Argumenten
  • Example#44 - Verwendung von Heredoc zur Initialisierung von statischen Werten
  • Example#45 - Verwendung von doppelten Anführungszeichen in Heredoc
  • Example#46 - Nowdoc-Beispiel für das Notieren von Strings
  • Example#47 - Nowdoc Beispiel für Strings mit Variablen
  • Example#48 - Beispiel für statische Daten
  • Example#49 - Beispiel für einfache Syntax
  • Example#50 - Negative numerische Indizes
  • Example#51 - Einige String-Beispiele
  • Example#52 - Beispiel für unzulässige String-Offsets
  • Example#53 - Ein einfaches Array
  • Example#54 - Beispiel für Typumwandlung und Überschreibung
  • Example#55 - Gemischte Int- und String-Schlüssel
  • Example#56 - Indizierte Arrays ohne Schlüssel
  • Example#57 - Schlüssel nicht bei allen Elementen
  • Example#58 - Beispiel für komplexe Typumwandlung und Überschreibung
  • Example#59 - Zugriff auf Array-Elemente
  • Example#60 - Array-Dereferenzierung
  • Example#61 - Einfaches Entpacken von Arrays
  • Example#62 - Entpacken eines Arrays mit doppeltem Schlüssel
  • Example#63 - Verwendung von array()
  • Example#64 - Sammlung
  • Example#65 - Elemente in der Schleife verändern
  • Example#66 - 1-basierte Indizes
  • Example#67 - Füllen eines Arrays
  • Example#68 - Ein Array sortieren
  • Example#69 - Rekursive und mehrdimensionale Arrays
  • Example#70 - Beispiele für Callback-Funktionen
  • Example#71 - Callback-Beispiel mit einem Closure
  • Example#72 - Iterable generator return type example
  • Example#73 - Typed pass-by-reference Parameters
  • Example#74 - Old way to make arguments nullable
  • Example#75 - Basic class type declaration
  • Example#76 - Basic interface type declaration
  • Example#77 - Basic return type declaration
  • Example#78 - Returning an object
  • Example#79 - Nullable argument type declaration
  • Example#80 - Nullable return type declaration
  • Example#81 - Class property type declaration
  • Example#82 - Strict typing for arguments values
  • Example#83 - Coercive typing for argument values
  • Example#84 - Strict typing for return values
  • Example#85 - Example of types being coerced into a type part of the union
  • Example#86 - Vorgabewerte uninitialisierter Variablen
  • Example#87 - Verwendung von global
  • Example#88 - Verwendung von $GLOBALS statt global
  • Example#89 - Beispiel zur Demonstration von Superglobalen und Geltungsbereich
  • Example#90 - Beispiel, das die Notwendigkeit von statischen Variablen demonstriert
  • Example#91 - Beispiel zur Verwendung statischer Variablen
  • Example#92 - Statische Variablen in rekursiven Funktionen
  • Example#93 - Statische Variablen deklarieren
  • Example#94 - Verwendung statischer Variablen in geerbten Methoden
  • Example#95 - Beispiel zu variablen Eigenschaften
  • Example#96 - Ein einfaches HTML-Formular
  • Example#97 - Zugriff auf die Daten eines einfachen POST-HTML-Formular
  • Example#98 - Komplexere Formular-Variablen
  • Example#99 - Ein setcookie-Beispiel
  • Example#100 - Gültige und ungültige Namen für Konstanten
  • Example#101 - Definition von Konstanten
  • Example#102 - Definition von Konstanten unter Verwendung des Schlüsselworts const
  • Example#103 - Assoziativität
  • Example#104 - Nicht definierte Auswertungsreihenfolge
  • Example#105 - +, - und . haben dieselbe Rangfolge (vor PHP 8.0.0)
  • Example#106 - Beispiel für die Inkrementierung von Zeichenketten im PERL-Stil
  • Example#107 - Umwandlung einer alphanumerischen Zeichenkette in eine Gleitkommazahl
  • Example#108 - Referenzzuweisung
  • Example#109 - Bitweise UND, ODER und XODER Operationen mit Ganzzahlen
  • Example#110 - Bitweise XODER Operationen mit Zeichenketten
  • Example#111 - Bit-Verschiebung mit Ganzzahlen
  • Example#112 - Boolesche und null-Vergleiche
  • Example#113 - Umschreibung von Standard-Array-Vergleichen
  • Example#114 - Zuweisen eines Standardwerts
  • Example#115 - Ungewöhnliches Verhalten des ternären Operators
  • Example#116 - Verkettung kurzer ternärer Operatoren
  • Example#117 - Zuweisung eines Standardwerts
  • Example#118 - Verschachtelung des null-Koaleszenz-Operators
  • Example#119 - Logische Operatoren erklärt
  • Example#120 - Array-Vergleiche
  • Example#121 - Die Verwendung von instanceof mit Klassen
  • Example#122 - Verwendung von instanceof mit ererbten Klassen
  • Example#123 - Verwendung von instanceof, um zu prüfen, ob ein Objekt nicht eine Instanz einer Klasse ist
  • Example#124 - Verwendung von instanceof mit Interfaces
  • Example#125 - Verwendung von instanceof mit anderen Variablen
  • Example#126 - Verwendung von instanceof um andere Variablen zu prüfen
  • Example#127 - Verwendung von instanceof um Konstanten zu prüfen
  • Example#128 - Verwendung von instanceof mit einem beliebigen Ausdruck
  • Example#129 - switch-Anweisung
  • Example#130 - Grundlegende Benutzung von match
  • Example#131 - Struktur eines match-Ausdrucks
  • Example#132 - Beispiel für einen unbehandelten Vergleichsausdruck
  • Example#133 - Prüfung von ganzzahligen Bereichen
  • Example#134 - Prüfung eines Textes auf enthaltene Zeichenfolgen
  • Example#135 - Tick Nutzungsbeispiel
  • Example#136 - Das Encoding eines Skripts deklarieren.
  • Example#137 - Grundlegendes include-Beispiel
  • Example#138 - Include in Funktionen
  • Example#139 - include über HTTP
  • Example#140 - Vergleichen des Rückgabewerts von include
  • Example#141 - include und return
  • Example#142 - Nutzung des Ausgabepuffers um eine Datei in einen String aufzunehmen
  • Example#143 - goto-Beispiel
  • Example#144 - goto-Schleifenbeispiel
  • Example#145 - Das wird nicht funktionieren
  • Example#146 - Pseudocode zur Demonstration der Nutzung von Funktionen
  • Example#147 - Bedingte Funktionen
  • Example#148 - Funktionen innerhalb von Funktionen
  • Example#149 - Rekursive Funktionen
  • Example#150 - Arrays an Funktionen übergeben
  • Example#151 - Liste von Funktionsparametern mit nachgestelltem Komma
  • Example#152 - Übergeben von Funktionsparametern als Verweis
  • Example#153 - Einsatz von Vorgabeparametern in Funktionen
  • Example#154 - Nichtskalare Typen als Vorgabewert
  • Example#155 - Verwendung von Objekten als Standardwerte (seit PHP 8.1.0)
  • Example#156 - Ungültige Verwendung von Vorgabewerten
  • Example#157 - Richtiger Einsatz von Vorgabewerten
  • Example#158 - Korrekte Verwendung von Funktionsparametern mit Standardwerten
  • Example#159 - Angabe von optionalen Parametern nach obligatorischen Parametern
  • Example#160 - Verwendung von ... für den Zugriff auf variable Parameter
  • Example#161 - Verwendung von ... zur Übergabe einer Parameterliste
  • Example#162 - Variable Parameter mit Typdeklaration
  • Example#163 - Syntax benannter Parameter
  • Example#164 - Positionsparameter im Vergleich zu benannten Parametern
  • Example#165 - Das gleiche Beispiel wie oben mit einer anderen Reihenfolge der Parameter
  • Example#166 - Kombinieren von benannten Parametern mit Positionsparametern
  • Example#167 - Die mehrfache Übergabe desselben Parameters erzeugt einen Fehler
  • Example#168 - Verwendung benannter Parameter nach dem Entpacken
  • Example#169 - Einsatz von return
  • Example#170 - Rückgabe mehrerer Werte als Array
  • Example#171 - Rückgabe von Referenzen aus Funktionen
  • Example#172 - Beispiel für Variablenfunktionen
  • Example#173 - Beispiel für eine Variablenmethode
  • Example#174 - Beispiel für Variablenmethoden mit statischen Eigenschaften
  • Example#175 - Komplexe Callables
  • Example#176 - Beispiel für eine anonyme Funktion
  • Example#177 - Beispiel für die Zuweisung einer anonymen Funktion
  • Example#178 - Erben von Variablen aus dem Eltern-Gültigkeitsbereich
  • Example#179 - Closures und Gültigkeitsbereiche
  • Example#180 - Automatisches Binden von $this
  • Example#181 - Versuch der Verwendung von $this innerhalb einer statischen anonymen Funktion
  • Example#182 - Versuch, ein Objekt an eine statische anonyme Funktion zu binden
  • Example#183 - Pfeilfunktionen binden Variablen automatisch per Wertübergabe
  • Example#184 - Pfeilfunktionen binden Variablen automatisch per Wertübergabe, selbst wenn sie verschachtelt sind
  • Example#185 - Beispiele von Pfeilfunktionen
  • Example#186 - Werte aus dem äußeren Geltungsbereich können nicht durch Pfeilfunktionen geändert werden
  • Example#187 - Einfaches Beispiel für eine Callback-Funktion als Objekt erster Klasse
  • Example#188 - Vergleich des Anwendungsbereichs von CallableExpr(...) und traditionellen Callback-Funktionen
  • Example#189 - Definition einer einfachen Klasse
  • Example#190 - Einige Beispiele für die Pseudovariable $this
  • Example#191 - Eine Instanz erzeugen
  • Example#192 - Erzeugen einer Instanz mit einem beliebigen Ausdruck
  • Example#193 - Objektzuweisung
  • Example#194 - Erzeugen neuer Objekte
  • Example#195 - Zugriff auf ein Mitglied eines neu erzeugten Objekts
  • Example#196 - Variablenzugriff vs. Methodenaufruf
  • Example#197 - Aufruf einer anonymen Funktion, die in einer Eigenschaft gespeichert ist
  • Example#198 - Einfache Vererbung
  • Example#199 - Kompatible Kindmethoden
  • Example#200 - Fataler Fehler, wenn eine Kindmethode einen Parameter entfernt
  • Example#201 - Fataler Fehler, wenn eine Kindmethode einen optionalen Parameter notwendig macht
  • Example#202 - Fehler, wenn benannte Parameter verwendet und diese in der Kindklasse umbenannt werden
  • Example#203 - Auflösung von Klassennamen
  • Example#204 - Fehlende Auflösung des Klassennamens
  • Example#205 - Namensauflösung eines Objekts
  • Example#206 - Nullsafe Operator
  • Example#207 - Deklaration von Eigenschaften
  • Example#208 - Beispiel von typisierten Eigenschaften
  • Example#209 - Auf Eigenschaften zugreifen
  • Example#210 - Beispiel für Readonly-Eigenschaften
  • Example#211 - Unzulässige Initialisierung von Readonly-Eigenschaften
  • Example#212 - Eine Konstante definieren und benutzen
  • Example#213 - Beispiel für ::class in einem Namensraum
  • Example#214 - Beispiel für Ausdrücke mit Klassenkonstanten
  • Example#215 - Sichtbarkeitsmodifizierer von Klassenkonstanten seit PHP 7.1.0
  • Example#216 - Autoload-Beispiel
  • Example#217 - Weiteres Autoload-Beispiel
  • Example#218 - Konstruktoren bei der Vererbung
  • Example#219 - Die Verwendung von Argumenten eines Konstruktors
  • Example#220 - Die Verwendung der Beförderung von Konstruktor-Eigenschaften
  • Example#221 - Verwendung von new bei Initialisierungen
  • Example#222 - Die Erzeugung über statische Methoden verwenden
  • Example#223 - Destruktor-Beispiel
  • Example#224 - Eigenschaftendeklaration
  • Example#225 - Methodendeklaration
  • Example#226 - Konstantendeklaration von PHP 7.1.0 an
  • Example#227 - Zugriff auf als private markierte Member des gleichen Objekttyps
  • Example#228 - Beispiel für Vererbung
  • Example#229 - Die überschreibende Methode deklariert keinen Rückgabetyp
  • Example#230 - Die überschreibende Methode deklariert einen falschen Rückgabetyp
  • Example#231 - Die überschreibende Methode deklariert einen falschen Rückgabetyp ohne Missbilligungs-Hinweis
  • Example#232 - :: außerhalb der Klassendefinition
  • Example#233 - :: innerhalb der Klassendefinition
  • Example#234 - Eine Vatermethode aufrufen
  • Example#235 - Beispiel für statische Methoden
  • Example#236 - Beispiel für statische Eigenschaften
  • Example#237 - Beispiel für abstrakte Klasse
  • Example#238 - Beispiel für abstrakte Klasse
  • Example#239 - Interface-Beispiel
  • Example#240 - Erweiterbare Interfaces
  • Example#241 - Varianzkompatibilität mit mehreren Schnittstellen
  • Example#242 - Interface-Mehrfachvererbung
  • Example#243 - Interfaces mit Konstanten
  • Example#244 - Interfaces mit abstrakten Klassen
  • Example#245 - Gleichzeitiges Erweitern und Implementieren
  • Example#246 - Trait-Beispiel
  • Example#247 - Rangfolge-Beispiel
  • Example#248 - Weiteres Beispiel für Rangfolge
  • Example#249 - Verwendung mehrerer Traits
  • Example#250 - Konfliktauflösung
  • Example#251 - Veränderung der Sichtbarkeit von Methoden
  • Example#252 - Trait-Zusammensetzung aus Traits
  • Example#253 - Ausdrücken von Anforderungen durch abstrakte Methoden
  • Example#254 - Statische Variablen
  • Example#255 - Statische Methoden
  • Example#256 - Statische Eigenschaften
  • Example#257 - Eigenschaften definieren
  • Example#258 - Konfliktauflösung
  • Example#259 - Definieren von Konstanten
  • Example#260 - Konfliktauflösung
  • Example#261 - Überladung von Eigenschaften mit den Methoden __get, __set, __isset und __unset
  • Example#262 - Überladung von Methoden mit den methoden __call und __callStatic
  • Example#263 - Einfache Objektiteration
  • Example#264 - Sleep- und Wakeup-Beispiel
  • Example#265 - Serialize und unserialize
  • Example#266 - Einfaches Beispiel
  • Example#267 - Nutzung von __invoke()
  • Example#268 - Nutzung von __invoke()
  • Example#269 - Verwendung von __set_state()
  • Example#270 - Verwendung von __debugInfo()
  • Example#271 - Beispiel für final-Methoden
  • Example#272 - Beispiel für finale Klassen
  • Example#273 - Beispiel für finale Konstanten (seit PHP 8.1.0)
  • Example#274 - Ein Objekt klonen
  • Example#275 - Zugriff auf ein Element eines soeben geklonten Objekts
  • Example#276 - Beispiel für Objektvergleiche
  • Example#277 - Nutzung von self::
  • Example#278 - Einfache Nutzung von static::
  • Example#279 - Nutzung von static:: außerhalb eines statischen Kontexts
  • Example#280 - Weitergegebene und nicht weitergegebene Aufrufe
  • Example#281 - Referenzen und Objekte
  • Example#282 - Beispiel für Namespace-Syntax
  • Example#283 - Einen einzelnen Namespace deklarieren
  • Example#284 - Einen einzelnen Namespace deklarieren
  • Example#285 - Einen einzelnen Namespace mit einer Hierarchie deklarieren
  • Example#286 - Mehrere Namespaces definieren, einfache Kombinationssyntax
  • Example#287 - Mehrere Namespaces definieren, geklammerte Syntax
  • Example#288 - Mehrere Namespaces und Code ohne Namespace deklarieren
  • Example#289 - Mehrere Namespaces und Code ohne Namespace deklarieren
  • Example#290 - Zugriff auf globale Klassen, Funktionen und Konstanten aus einem Namespace
  • Example#291 - Dynamischer Zugriff auf Elemente
  • Example#292 - Dynamischer Zugriff auf Elemente mit Namespace
  • Example#293 - __NAMESPACE__-Beispiel, Code mit Namespace
  • Example#294 - __NAMESPACE__-Beispiel, globaler Code
  • Example#295 - __NAMESPACE__ zur dynamischen Namenszusammensetzung verwenden
  • Example#296 - Der namespace-Operator, innerhalb eines Namespace
  • Example#297 - Der namespace-Operator, in globalem Code
  • Example#298 - Aliase/Importieren mit dem use-Operator
  • Example#299 - Aliase/Importieren mit dem use-Operator, mehrere use-Ausdrücke kombiniert
  • Example#300 - Importieren und dynamische Namen
  • Example#301 - Importieren und vollständig qualifizierte Namen
  • Example#302 - Ungültige Importregel
  • Example#303 - Verwenden der Spezifikation des globalen Namensraumes
  • Example#304 - Zugriff auf globale Klasse innerhalb eines Namespace
  • Example#305 - Rückgriff auf globale Funktionen/Konstanten innerhalb eines Namespace
  • Example#306 - Illustration der Namensauflösung
  • Example#307 - Zugriff auf globale Klassen außerhalb eines Namespace
  • Example#308 - Zugriff auf globale Klassen außerhalb eines Namespace
  • Example#309 - Zugriff auf interne Klassen in Namespaces
  • Example#310 - Zugriff auf interne Klassen, Funktionen oder Konstanten in Namespaces
  • Example#311 - Vollständig qualifizierte Namen
  • Example#312 - Qualifizierte Namen
  • Example#313 - Unqualifizierter Klassennamen
  • Example#314 - Unqualifizierte Funktions- oder Konstantennamen
  • Example#315 - Gefahren von Namespacenamen in Strings mit doppelten Anführungszeichen
  • Example#316 - Undefinierte Konstanten
  • Example#317 - Spezielle Konstanten
  • Example#318 - Grundlegende eingeschränkte Werte
  • Example#319 - Erweiterte exklusive Werte
  • Example#320 - Fehlermeldungen in Exceptions umwandeln
  • Example#321 - Eine Exception auslösen
  • Example#322 - Exceptionbehandlung mit einem finally-Block
  • Example#323 - Wechselwirkung zwischen dem finally-Block und return
  • Example#324 - Verschachtelte Exceptions
  • Example#325 - Behandlung mehrerer Exceptions in einem Catch-Block
  • Example#326 - Catch-Block ohne Angabe einer Variablen
  • Example#327 - Als Ausdruck Auslösen
  • Example#328 - Die eingebaute Exceptionklasse
  • Example#329 - Die Exceptionklasse erweitern
  • Example#330 - Grundlegende Verwendung
  • Example#331 - Implementierung von range als Generator
  • Example#332 - Ein einfaches Beispiel zum liefern (yielding) von Werten
  • Example#333 - Produzieren eines Schlüssel/Wert-Paares
  • Example#334 - Produzieren von nulls
  • Example#335 - Produzieren von Werten als Referenz
  • Example#336 - yield from mit iterator_to_array
  • Example#337 - Grundlegende Verwendung von yield from
  • Example#338 - yield from und Rückgabewerte
  • Example#339 - Implementierung optionaler Methoden einer Schnittstelle mit Hilfe von Attributen
  • Example#340 - Syntax von Attributen
  • Example#341 - Lesen von Attributen mit der Reflection-API
  • Example#342 - Lesen bestimmter Attribute mit der Reflection-API
  • Example#343 - Einfache Attributklasse
  • Example#344 - Verwendung der Zielspezifikation, um die Verwendung von Attributen zu beschränken
  • Example#345 - Verwendung von IS_REPEATABLE um ein Attribut mehrfach in einer Deklaration zu erlauben
  • Example#346 - Referenzen mit undefinierten Variablen benutzen
  • Example#347 - Referenzieren globaler Variablen innerhalb von Funktionen
  • Example#348 - Referenzen und die foreach-Anweisung
  • Example#349 - $GLOBALS-Beispiel
  • Example#350 - Das Schreiben des gesamten $GLOBALS führt zu einem Fehler
  • Example#351 - $_SERVER-Beispiel
  • Example#352 - $_GET-Beispiel
  • Example#353 - $_POST-Beispiel
  • Example#354 - $_ENV-Beispiel
  • Example#355 - $_COOKIE-Beispiel
  • Example#356 - $php_errormsg-Beispiel
  • Example#357 - $http_response_header-Beispiel
  • Example#358 - $argc-Beispiel
  • Example#359 - $argv-Beispiel
  • Example#360 - Exception::getMessage-Beispiel
  • Example#361 - Exception::getPrevious Beispiel
  • Example#362 - Exception::getCode-Beispiel
  • Example#363 - Exception::getFile-Beispiel
  • Example#364 - Exception::getLine-Beispiel
  • Example#365 - Exception::getTrace-Beispiel
  • Example#366 - Exception::getTraceAsString-Beispiel
  • Example#367 - Exception::__toString-Beispiel
  • Example#368 - Verwenden von set_error_handler zum Verändern von Fehlermeldungen innerhalb ErrorException.
  • Example#369 - ErrorException::getSeverity-Beispiel
  • Example#370 - Error::getMessage-Beispiel
  • Example#371 - Error::getPrevious-Beispiel
  • Example#372 - Error::getCode-Beispiel
  • Example#373 - Error::getFile-Beispiel
  • Example#374 - Error::getLine-Beispiel
  • Example#375 - Error::getTrace-Beispiel
  • Example#376 - Error::getTraceAsString-Beispiel
  • Example#377 - Error::__toString-Beispiel
  • Example#378 - Grundlegende Nutzung
  • Example#379 - Grundlegende Verwendung
  • Example#380 - Grundlegende Verwendung
  • Example#381 - ArrayAccess::offsetExists-Beispiel
  • Example#382 - Grundlegende Verwendung
  • Example#383 - Closure::bind-Beispiel
  • Example#384 - Closure::bindTo-Beispiel
  • Example#385 - Closure::call-Beispiel
  • Example#386 - Erzeugt durch eine Typumwandlung in ein Objekt
  • Example#387 - Erzeugt mittels json_decode
  • Example#388 - Deklarieren dynamischer Eigenschaften
  • Example#389 - Generator::getReturn-Beispiel
  • Example#390 - Generator::key-Beispiel
  • Example#391 - Werte mittels Generator::send einfügen
  • Example#392 - Eine Exception in einen Generator werfen
  • Example#393 - Grundlegende Verwendung von WeakReference
  • Example#394 - Weakmap-Anwendungsbeispiel
  • Example#395 - Grundlegende Verwendung von Stringable
  • Example#396 - Grundlegende Verwendung
  • Example#397 - Grundlegende Verwendung
  • Example#398 - Grundlegende Verwendung
  • Example#399 - Übergabe eines SensitiveParameterValue-Objekts an var_dump
  • Example#400 - SensitiveParameterValue::getValue-Beispiel
  • Example#401 - Grundlegendes Beispiel für die Verwendung von bindto
  • Example#402 - Abrufen einer Seite mit Übermittlung von POST-Daten
  • Example#403 - Weiterleitungen ignorieren, aber Kopfzeilen und Inhalt abrufen
  • Example#404 - Grundlegendes Beispiel für die Verwendung von password
  • Example#405 - Detecting which URL we ended up on after redirects
  • Example#406 - php://temp/maxmemory
  • Example#407 - php://filter/resource=<stream to be filtered>
  • Example#408 - php://filter/read=<filter list to apply to read chain>
  • Example#409 - php://filter/write=<filter list to apply to write chain>
  • Example#410 - php://memory and php://temp are not reusable
  • Example#411 - Print data:// contents
  • Example#412 - Fetch the media type
  • Example#413 - Basic usage
  • Example#414 - Opening a stream from an active connection
  • Example#415 - This $session variable must be kept available!
  • Example#416 - Traversing a RAR archive
  • Example#417 - Opening an encrypted file (header encryption)
  • Example#418 - Schlechte Variablenprüfung führt zu....
  • Example#419 - ... Ein Angriff auf das Dateisystem
  • Example#420 - Etwas sicherere Prüfung des Dateinamens
  • Example#421 - Sicherere Dateinamensprüfung
  • Example#422 - Skript mit Nullbyte-Verwundbarkeit
  • Example#423 - Korrekte Validierung der Eingabe
  • Example#424 - Hashen eines Passwortfeldes
  • Example#425 - Die Ergebnisliste in mehrere Seiten aufsplitten ... und Superuser anlegen (PostgreSQL)
  • Example#426 - Artikel auflisten ... und ein paar Passwörter (beliebiger Datenbankserver)
  • Example#427 - Vom Zurücksetzen eines Passworts ... zum Erlangen von mehr Rechten (beliebiger Datenbankserver)
  • Example#428 - Angriff auf das Betriebssystem des Datenbank-Hosts (MSSQL-Server)
  • Example#429 - Ein sicherer Weg, eine Abfrage zu erstellen
  • Example#430 - Variablen mit einer eigenen HTML-Seite angreifen
  • Example#431 - Ausnutzen von gebräuchlichen Debugging-Variablen
  • Example#432 - Gefährliche Variablen mit E_ALL finden
  • Example#433 - Gefährliche Verwendung von Variablen
  • Example#434 - PHP als andere Sprache ausgeben
  • Example#435 - Verwenden von unbekannten Typen für PHP-Dateierweiterungen
  • Example#436 - Verwenden von HTML-Typen für PHP-Dateierweiterungen
  • Example#437 - Beispiel: Basic-HTTP-Authentifizierung
  • Example#438 - Beispiel: Digest-HTTP-Authentifizierung
  • Example#439 - HTTP-Authentifizierung, mit erneuter Anforderung von Name/Passwort
  • Example#440 - Ein einfaches XForms-Suchformular
  • Example#441 - XForm verwenden, um $_POST zu bestücken
  • Example#442 - Formular zum Hochladen von Dateien
  • Example#443 - Dateiuploads prüfen
  • Example#444 - Hochladen eines Arrays von Dateien
  • Example#445 - Hochladen mehrerer Dateien
  • Example#446 - Hochladen eines kompletten Verzeichnisses
  • Example#447 - Speichern von HTTP-PUT-Dateien
  • Example#448 - Den Titel einer entfernten Seite auslesen
  • Example#449 - Daten auf einen entfernten Server speichern
  • Example#450 - Beispiel, welches den Unterschied zur CGI-SAPI verdeutlicht:
  • Example#451 - Beispiel für die Verwendung von -d zum Setzen einer INI-Direktive
  • Example#452 - Ausgabe der geladenen PHP- und Zend-Module
  • Example#453 - Syntaxfehler beim Verwenden von doppelten Anführungszeichen
  • Example#454 - Verwendung einfacher Anführungszeichen, um ein Ersetzen der Variablen durch die Shell zu verhindern
  • Example#455 - Nutzung der Optionen -B, -R und -E, um die Anzahl der Zeilen in einem Projekt zu zählen.
  • Example#456 - Nutzung von -v, um den SAPI-Namen, sowie die PHP- und Zend-Version zu ermitteln
  • Example#457 - --ini-Beispiel
  • Example#458 - Einfache --rf-Nutzung
  • Example#459 - --rc-Beispiel
  • Example#460 - --re-Beispiel
  • Example#461 - --ri-Beispiel
  • Example#462 - PHP als Shellskript ausführen
  • Example#463 - Ein Skript, das von der Kommandozeile aus ausgeführt werden soll (script.php)
  • Example#464 - Batchdatei zur Ausführung eines Kommandozeilen-Skripts in PHP (script.bat)
  • Example#465 - Ausführung von Code in der interaktiven Shell
  • Example#466 - Tabulator-Autovervollständigung
  • Example#467 - Setzen von php.ini-Optionen in der interaktiven Shell
  • Example#468 - Starten des Webservers
  • Example#469 - Starten mit einer expliziten Document-Root
  • Example#470 - Nutzung eines Router-Skripts
  • Example#471 - Prüfung auf die Verwendung des CLI-Webservers
  • Example#472 - Behandlung nicht unterstützter Dateitypen
  • Example#473 - Zugriff auf den CLI-Webserver von anderen Computern aus
  • Example#474 - Erstellen eines neuen zval-Containers
  • Example#475 - Anzeigen von zval-Informationen
  • Example#476 - Erhöhen des Referenzzählers eines Zval
  • Example#477 - Verringern des zval-Referenzzählers
  • Example#478 - Erstellen eines Array-Zvals
  • Example#479 - Hinzufügen eines bereits vorhandenen Elements zu einem Array
  • Example#480 - Entfernen eines Elements aus einem Array
  • Example#481 - Hinzufügen des Arrays als Element von sich selbst
  • Example#482 - Aufheben von $a
  • Example#483 - Beispiel für die Speichernutzung
  • Example#484 - Einfluss der GC auf die Leistung
  • Example#485 - Ausführen des obigen Skripts
  • Example#486 - PHP neu kompilieren, um das GC-Benchmarking zu aktivieren
  • Example#487 - GC-Statistik
  • Example#488 - all_probes.d für die Verfolgung aller statischen PHP-Sonden mit DTrace
  • Example#489 - all_probes.stp - Verfolgung aller statischen PHP-Sonden mit SystemTap
  • Example#490 - A apcu_add example
  • Example#491 - A apcu_cache_info example
  • Example#492 - apcu_cas example
  • Example#493 - apcu_dec example
  • Example#494 - A apcu_delete example
  • Example#495 - An apcu_entry example
  • Example#496 - apcu_exists example
  • Example#497 - A apcu_fetch example
  • Example#498 - apcu_inc example
  • Example#499 - A apcu_key_info example
  • Example#500 - A apcu_sma_info example
  • Example#501 - A apcu_store example
  • Example#502 - A APCUIterator::__construct example
  • Example#503 - Fehlerbehandlung in einem Script
  • Example#504 - debug_backtrace-Beispiel
  • Example#505 - debug_print_backtrace-Beispiel
  • Example#506 - An error_clear_last example
  • Example#507 - error_get_last-Beispiel
  • Example#508 - error_log-Beispiele
  • Example#509 - error_reporting-Beispiel
  • Example#510 - restore_error_handler-Beispiel
  • Example#511 - restore_exception_handler-Beispiel
  • Example#512 - Fehlerbehandlung mit set_error_handler und trigger_error
  • Example#513 - set_exception_handler-Beispiel
  • Example#514 - trigger_error-Beispiel
  • Example#515 - Calling a function from shared library
  • Example#516 - Calling a function, returning a structure through an argument
  • Example#517 - Accessing existing C variables
  • Example#518 - Creating and Modifying C variables
  • Example#519 - Working with C arrays
  • Example#520 - Working with C enums
  • Example#521 - Assigning a PHP Closure to a C function pointer
  • Example#522 - Output-Control-Beispiel
  • Example#523 - URL-Rewriter-Beispiel
  • Example#524 - ob_end_clean-Beispiel
  • Example#525 - ob_end_flush-Beispiel
  • Example#526 - A simple ob_get_clean example
  • Example#527 - Ein einfaches ob_get_contents-Beispiel
  • Example#528 - ob_get_flush example
  • Example#529 - A simple ob_get_length example
  • Example#530 - Array returned when full_status is false
  • Example#531 - Array returned when full_status is true
  • Example#532 - ob_list_handlers example
  • Example#533 - Beispiel einer benutzerdefinierten Callback-Funktion
  • Example#534 - Erzeugen eines nicht löschbaren Ausgabepuffers
  • Example#535 - output_add_rewrite_var-Beispiel
  • Example#536 - output_reset_rewrite_vars example
  • Example#537 - assert_options-Beispiel
  • Example#538 - assert-Beispiel
  • Example#539 - Verwenden einer benutzerdefinierten Meldung
  • Example#540 - Verwenden einer benutzerdefinierten Exception-Klasse
  • Example#541 - cli_get_process_title example
  • Example#542 - cli_set_process_title example
  • Example#543 - dl-Beispiele
  • Example#544 - extension_loaded-Beispiel
  • Example#545 - A gc_enabled example
  • Example#546 - gc_status Usage
  • Example#547 - get_current_user-Beispiel
  • Example#548 - get_defined_constants Example
  • Example#549 - Gibt alle XML-Funktionen aus
  • Example#550 - get_include_path example
  • Example#551 - get_included_files-Beispiel
  • Example#552 - get_loaded_extensions-Beispiel
  • Example#553 - Unfiltered get_resources
  • Example#554 - Filtered get_resources
  • Example#555 - getenv-Beispiel
  • Example#556 - getlastmod-Beispiel
  • Example#557 - getopt example: The basics
  • Example#558 - getopt example: Introducing long options
  • Example#559 - getopt example: Passing multiple options as one
  • Example#560 - getopt example: Using rest_index
  • Example#561 - getrusage-Beispiel
  • Example#562 - ini_get_all examples
  • Example#563 - Disabling details
  • Example#564 - A few ini_get examples
  • Example#565 - A few ini_parse_quantity examples
  • Example#566 - ini_restore example
  • Example#567 - Setting an ini option
  • Example#568 - A memory_get_usage example
  • Example#569 - memory_reset_peak_usage example
  • Example#570 - php_ini_loaded_file example
  • Example#571 - Ein einfaches Beispiel um zurückgegebene ini-Dateien aufzulisten
  • Example#572 - php_sapi_name-Beispiel
  • Example#573 - Some php_uname examples
  • Example#574 - A few OS related constant examples
  • Example#575 - Prints the general credits
  • Example#576 - Prints the core developers and the documentation group
  • Example#577 - Printing all the credits
  • Example#578 - phpinfo-Beispiel
  • Example#579 - phpversion-Beispiel
  • Example#580 - PHP_VERSION_ID-Beispiel und -Verwendung
  • Example#581 - Setzen einer Umgebungsvariablen
  • Example#582 - restore_include_path example
  • Example#583 - set_include_path-Beispiel
  • Example#584 - Den include-path erweitern
  • Example#585 - sys_get_temp_dir example
  • Example#586 - version_compare-Beispiele
  • Example#587 - zend_thread_id-Beispiel
  • Example#588 - zend_version-Beispiel
  • Example#589 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#590 - A runkit7_function_add example
  • Example#591 - A runkit7_function_copy example
  • Example#592 - A runkit7_function_redefine example
  • Example#593 - runkit7_method_add example
  • Example#594 - runkit7_method_copy example
  • Example#595 - runkit7_method_redefine example
  • Example#596 - runkit7_method_remove example
  • Example#597 - runkit7_method_rename example
  • Example#598 - runkit7_zval_inspect example
  • Example#599 - Basic uopz_add_function Usage
  • Example#600 - uopz_allow_exit example
  • Example#601 - uopz_backup example
  • Example#602 - uopz_compose example
  • Example#603 - uopz_copy example
  • Example#604 - Basic uopz_del_function Usage
  • Example#605 - uopz_delete example
  • Example#606 - uopz_delete class example
  • Example#607 - uopz_extend example
  • Example#608 - uopz_flags example
  • Example#609 - "Unfinalize" a Class
  • Example#610 - uopz_function example
  • Example#611 - uopz_function class example
  • Example#612 - uopz_get_exit_status example
  • Example#613 - Basic uopz_get_hook Usage
  • Example#614 - uopz_get_mock example
  • Example#615 - Basic uopz_get_property Usage
  • Example#616 - uopz_get_return example
  • Example#617 - Basic uopz_get_static Usage
  • Example#618 - uopz_implement example
  • Example#619 - uopz_overload example
  • Example#620 - uopz_redefine example
  • Example#621 - uopz_rename example
  • Example#622 - uopz_rename class example
  • Example#623 - uopz_restore example
  • Example#624 - Basic uopz_set_hook Usage
  • Example#625 - uopz_set_mock example
  • Example#626 - uopz_set_mock example
  • Example#627 - uopz_set_mock and static members
  • Example#628 - Basic uopz_set_property Usage
  • Example#629 - uopz_set_return example
  • Example#630 - uopz_set_return example
  • Example#631 - uopz_set_return class example
  • Example#632 - Basic uopz_set_static Usage
  • Example#633 - uopz_undefine example
  • Example#634 - Basic uopz_unset_hook Usage
  • Example#635 - uopz_unset_mock example
  • Example#636 - uopz_unset_return example
  • Example#637 - wincache.ignorelist example
  • Example#638 - Authentication configuration for wincache.php
  • Example#639 - Enabling WinCache session handler
  • Example#640 - Enabling WinCache functions reroutes
  • Example#641 - Reroute.ini file content
  • Example#642 - A wincache_fcache_fileinfo example
  • Example#643 - A wincache_fcache_meminfo example
  • Example#644 - Using wincache_lock
  • Example#645 - A wincache_ocache_fileinfo example
  • Example#646 - A wincache_ocache_meminfo example
  • Example#647 - A wincache_refresh_if_changed example
  • Example#648 - A wincache_rplist_fileinfo example
  • Example#649 - A wincache_rplist_meminfo example
  • Example#650 - A wincache_scache_info example
  • Example#651 - A wincache_scache_meminfo example
  • Example#652 - wincache_ucache_add with key as a string
  • Example#653 - wincache_ucache_add with key as an array
  • Example#654 - Using wincache_ucache_cas
  • Example#655 - using wincache_ucache_clear
  • Example#656 - Using wincache_ucache_dec
  • Example#657 - Using wincache_ucache_delete with key as a string
  • Example#658 - Usingwincache_ucache_delete with key as an array
  • Example#659 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#660 - Using wincache_ucache_exists
  • Example#661 - wincache_ucache_get with key as a string
  • Example#662 - wincache_ucache_get with key as an array
  • Example#663 - Using wincache_ucache_inc
  • Example#664 - Using wincache_ucache_info
  • Example#665 - A wincache_ucache_meminfo example
  • Example#666 - wincache_ucache_set with key as a string
  • Example#667 - wincache_ucache_set with key as an array
  • Example#668 - Using wincache_unlock
  • Example#669 - Xhprof example with the optional GUI
  • Example#670 - xhprof_disable example
  • Example#671 - xhprof_enable examples
  • Example#672 - xhprof_sample_disable example
  • Example#673 - Make sure the item is stored
  • Example#674 - Using CHAP passwords
  • Example#675 - radius_acct_open example
  • Example#676 - radius_add_server example
  • Example#677 - radius_auth_open example
  • Example#678 - radius_create_request example
  • Example#679 - radius_cvt_addr example
  • Example#680 - radius_cvt_int example
  • Example#681 - radius_cvt_string example
  • Example#682 - radius_get_attr example
  • Example#683 - radius_get_tagged_attr_data example
  • Example#684 - radius_get_tagged_attr_tag example
  • Example#685 - radius_get_vendor_attr example
  • Example#686 - radius_put_attr example
  • Example#687 - radius_put_int example
  • Example#688 - radius_put_string example
  • Example#689 - radius_put_vendor_attr example
  • Example#690 - Readline-Callback-Interface-Beispiel
  • Example#691 - readline-Beispiel
  • Example#692 - Ein kleines bzip2-Beispiel
  • Example#693 - Komprimierung von Daten
  • Example#694 - Dekomprimieren einer Zeichenkette
  • Example#695 - bzerror-Beispiel
  • Example#696 - bzopen-Beispiel
  • Example#697 - bzread-Beispiel
  • Example#698 - bzwrite-Beispiel
  • Example#699 - Using an external file
  • Example#700 - Using a file within a phar archive
  • Example#701 - Converting a phar archive from phar to tar file format
  • Example#702 - phar.cache_list usage example
  • Example#703 - A Phar::addEmptyDir example
  • Example#704 - A Phar::addFile example
  • Example#705 - A Phar::addFromString example
  • Example#706 - A Phar::apiVersion example
  • Example#707 - A Phar::buildFromDirectory example
  • Example#708 - A Phar::buildFromIterator with SplFileInfo
  • Example#709 - A Phar::buildFromIterator with other iterators
  • Example#710 - A Phar::canCompress example
  • Example#711 - A Phar::canWrite example
  • Example#712 - A Phar::compress example
  • Example#713 - A Phar::compressFiles example
  • Example#714 - A Phar::__construct example
  • Example#715 - A Phar::convertToData example
  • Example#716 - A Phar::convertToExecutable example
  • Example#717 - A Phar::copy example
  • Example#718 - A Phar::count example
  • Example#719 - A Phar::createDefaultStub example
  • Example#720 - A Phar::decompress example
  • Example#721 - A Phar::decompressFiles example
  • Example#722 - A Phar::delMetaData example
  • Example#723 - A Phar::delete example
  • Example#724 - A Phar::extractTo example
  • Example#725 - A Phar::getMetadata example
  • Example#726 - A Phar::getStub example
  • Example#727 - A Phar::hasMetadata example
  • Example#728 - A Phar::interceptFileFuncs example
  • Example#729 - A Phar::interceptFileFuncs example
  • Example#730 - A Phar::isBuffering example
  • Example#731 - A Phar::isCompressed example
  • Example#732 - A Phar::loadPhar example
  • Example#733 - A Phar::mapPhar example
  • Example#734 - A Phar::mount example
  • Example#735 - A Phar::mungServer example
  • Example#736 - A Phar::offsetExists example
  • Example#737 - Phar::offsetGet example
  • Example#738 - A Phar::offsetSet example
  • Example#739 - A Phar::offsetUnset example
  • Example#740 - A Phar::running example
  • Example#741 - A Phar::setAlias example
  • Example#742 - A Phar::setDefaultStub example
  • Example#743 - A Phar::setMetadata example
  • Example#744 - A Phar::setStub example
  • Example#745 - A Phar::startBuffering example
  • Example#746 - A Phar::stopBuffering example
  • Example#747 - A Phar::unlinkArchive example
  • Example#748 - A Phar::webPhar example
  • Example#749 - A PharData::addEmptyDir example
  • Example#750 - A PharData::addFile example
  • Example#751 - A PharData::addFromString example
  • Example#752 - A PharData::buildFromDirectory example
  • Example#753 - A PharData::buildFromIterator with SplFileInfo
  • Example#754 - A PharData::buildFromIterator with other iterators
  • Example#755 - A PharData::compress example
  • Example#756 - A PharData::compressFiles example
  • Example#757 - A PharData::__construct example
  • Example#758 - A PharData::convertToData example
  • Example#759 - A PharData::convertToExecutable example
  • Example#760 - A PharData::copy example
  • Example#761 - A PharData::decompress example
  • Example#762 - A PharData::decompressFiles example
  • Example#763 - A PharData::delMetaData example
  • Example#764 - A PharData::delete example
  • Example#765 - A PharData::extractTo example
  • Example#766 - A PharData::offsetSet example
  • Example#767 - A PharData::offsetUnset example
  • Example#768 - A Phar::setMetadata example
  • Example#769 - A PharFileInfo::chmod example
  • Example#770 - A PharFileInfo::compress example
  • Example#771 - A PharFileInfo::__construct example
  • Example#772 - A PharFileInfo::decompress example
  • Example#773 - A PharFileInfo::delMetaData example
  • Example#774 - A PharFileInfo::getCRC32 example
  • Example#775 - A PharFileInfo::getCompressedSize example
  • Example#776 - A PharFileInfo::getMetadata example
  • Example#777 - A PharFileInfo::getPharFlags example
  • Example#778 - A PharFileInfo::isCRCChecked example
  • Example#779 - A PharFileInfo::isCompressed example
  • Example#780 - A PharFileInfo::setMetadata example
  • Example#781 - Rar Installation
  • Example#782 - On-the-fly decompression
  • Example#783 - RAR extension filesystem extraction example
  • Example#784 - Objektorientierter Stil
  • Example#785 - Prozeduraler Stil
  • Example#786 - Objektorientierter Stil
  • Example#787 - Prozeduraler Stil
  • Example#788 - Objektorientierter Stil
  • Example#789 - Prozeduraler Stil
  • Example#790 - Objektorientierter Stil
  • Example#791 - Prozeduraler Stil
  • Example#792 - Objektorientierter Stil
  • Example#793 - Prozeduraler Stil
  • Example#794 - Objektorientierter Stil
  • Example#795 - Prozeduraler Stil
  • Example#796 - Objektorientierter Stil
  • Example#797 - Prozeduraler Stil
  • Example#798 - Volume Callback
  • Example#799 - Objektorientierter Stil
  • Example#800 - Prozeduraler Stil
  • Example#801 - RarArchive::__toString example
  • Example#802 - RarEntry::extract example
  • Example#803 - How to extract all files in archive:
  • Example#804 - RarEntry::getAttr example
  • Example#805 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#806 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#807 - RarEntry::getMethod example
  • Example#808 - RarEntry::getName example
  • Example#809 - RarEntry::getPackedSize example
  • Example#810 - RarEntry::getStream example
  • Example#811 - RarEntry::getUnpackedSize example
  • Example#812 - RarEntry::getVersion example
  • Example#813 - RarException::isUsingExceptions example
  • Example#814 - RarException::setUsingExceptions example
  • Example#815 - Erstellen eines Zip-Archivs
  • Example#816 - Ausgabe eines detailierten Archivlistings
  • Example#817 - Zip Stream Wrapper, Auslesen von OpenOffice Metainformationen
  • Example#818 - Zip Beispiel
  • Example#819 - Erstellt ein neues Verzeichnis im Archiv
  • Example#820 - Öffnen und hinzufügen
  • Example#821 - Einen Eintrag zu einem neuen Archiv hinzufügen
  • Example#822 - Eine Datei zu einem Verzeichnis innerhalb eines Archivs hinzufügen
  • Example#823 - ZipArchive::addGlob example
  • Example#824 - ZipArchive::addPattern example
  • Example#825 - Löschen einer Datei aus dem Archiv unter Verwendung ihres Index
  • Example#826 - Eine Datei und ein Verzeichnis unter Verwendung ihrer Namen aus einem Archiv löschen
  • Example#827 - Alle Einträge extrahieren
  • Example#828 - Zwei Einträge extrahieren
  • Example#829 - Einen Archivkommentar ausgeben
  • Example#830 - Test if archive is a torrentzip format
  • Example#831 - Einen Eintragskommentar ausgeben
  • Example#832 - Einen Eintragskommentar ausgeben
  • Example#833 - Extract all entries with Unix rights
  • Example#834 - Den Dateiinhalt auslesen
  • Example#835 - Den Dateiinhalt auslesen
  • Example#836 - Ein Bild aus einem ZIP-Eintrag konvertieren
  • Example#837 - ZipArchive::getNameIndex-Beispiel
  • Example#838 - Den Eintragsinhalt mit fread abrufen und speichern
  • Example#839 - Das gleiche wie im vorigen Beispiel aber mit fopen und dem ZIP-Streamwrapper
  • Example#840 - Streamwrapper und Bild, kann auch mit der XML-Funktion verwendet werden
  • Example#841 - Get the entry contents with fread and store it
  • Example#842 - Get the entry contents with fread and store it
  • Example#843 - Ein Archiv erstellen und es mit locateName verwenden
  • Example#844 - Öffnen und extrahieren
  • Example#845 - Ein Archiv erstellen
  • Example#846 - Erstellen eines temporären Archivs
  • Example#847 - Archive a file
  • Example#848 - Archive a file
  • Example#849 - Einen Eintrag umbenennen
  • Example#850 - Einen Eintrag umbenennen
  • Example#851 - Open and replace
  • Example#852 - Ein Archiv erstellen und einen Kommentar hinzufügen
  • Example#853 - Create a torrentzip archive
  • Example#854 - Ein Archiv öffnen und für einen Eintrag einen Kommentar hinzufügen
  • Example#855 - Ein Archiv öffnen und für einen Eintrag einen Kommentar hinzufügen
  • Example#856 - Add files with different compression methods to an archive
  • Example#857 - Add files with different compression methods to an archive
  • Example#858 - Add file and set compression method
  • Example#859 - Archive and encrypt a file
  • Example#860 - Archive a file, with its Unix rights
  • Example#861 - Archive a file
  • Example#862 - Archive a file
  • Example#863 - Die Statusinformation eines Eintrags ausgeben
  • Example#864 - Die Statusinformation eines Eintrags ausgeben
  • Example#865 - Ein kleines Beispiel zu Zlib
  • Example#866 - Arbeiten mit den inkrementellen Kompriemierungs- und Dekomprimierungs-API
  • Example#867 - gzclose-Beispiel
  • Example#868 - gzcompress-Beispiel
  • Example#869 - gzdeflate-Beispiel
  • Example#870 - Creating a gzip file
  • Example#871 - gzeof-Beispiel
  • Example#872 - gzfile-Beispiel
  • Example#873 - gzgetc-Beispiel
  • Example#874 - gzgets example
  • Example#875 - gzgetss-Beispiel
  • Example#876 - gzinflate-Beispiel
  • Example#877 - gzopen-Beispiel
  • Example#878 - gzpassthru-Beispiel
  • Example#879 - gzread-Beispiel
  • Example#880 - gzseek-Beispiel
  • Example#881 - gzuncompress-Beispiel
  • Example#882 - gzwrite-Beispiel
  • Example#883 - ob_gzhandler example
  • Example#884 - zlib_encode-Beispiel
  • Example#885 - hash_algos-Beispiel
  • Example#886 - hash_copy-Beispiel
  • Example#887 - hash_equals example
  • Example#888 - hash_file-Beispiel
  • Example#889 - hash_hkdf example
  • Example#890 - hash_hmac_algos example
  • Example#891 - hash_hmac_file-Beispiel
  • Example#892 - hash_hmac-Beispiel
  • Example#893 - Beispiel für schrittweises Hashing
  • Example#894 - hash_pbkdf2 example, basic usage
  • Example#895 - hash_update_stream-Beispiel
  • Example#896 - hash-Beispiel
  • Example#897 - mcrypt_create_iv Example
  • Example#898 - mcrypt_enc_get_algorithms_name example
  • Example#899 - mcrypt_enc_get_modes_name example
  • Example#900 - mcrypt_enc_get_supported_key_sizes example
  • Example#901 - mcrypt_encrypt Example
  • Example#902 - mcrypt_get_block_size example
  • Example#903 - mcrypt_get_cipher_name Example
  • Example#904 - mcrypt_get_iv_size Example
  • Example#905 - mcrypt_get_key_size Example
  • Example#906 - mcrypt_list_algorithms Example
  • Example#907 - mcrypt_list_modes Example
  • Example#908 - mcrypt_module_open Examples
  • Example#909 - Using mcrypt_module_open in encryption
  • Example#910 - mcrypt_module_self_test example
  • Example#911 - mdecrypt_generic Example
  • Example#912 - Computes the MD5 digest and hmac and print it out as hex
  • Example#913 - Alle Hashes durchlaufen
  • Example#914 - mhash_get_block_size-Beispiel
  • Example#915 - mhash_get_hash_name-Beispiel
  • Example#916 - openssl_cipher_iv_length example
  • Example#917 - openssl_cipher_key_length example
  • Example#918 - openssl_cms_sign example
  • Example#919 - openssl_csr_export_to_file-Beispiel
  • Example#920 - openssl_csr_export-Beispiel
  • Example#921 - openssl_csr_get_public_key-Beispiel
  • Example#922 - openssl_csr_get_subject-Beispiel
  • Example#923 - Erzeugen eines selbstsignierten Zertifikats
  • Example#924 - Erzeugen eines selbstsignierten ECC-Zertifikats (von PHP 7.1.0 an)
  • Example#925 - openssl_csr_sign-Beispiel - Signieren eines CSR (wie eine eigene CA implementiert wird)
  • Example#926 - Compute a shared secret
  • Example#927 - Generate a DH public/private keypair in php
  • Example#928 - AES Authenticated Encryption im GCM-Modus, Beispiel für PHP 7.1+
  • Example#929 - AES Authenticated Encryption, Beispiel vor PHP 7.1
  • Example#930 - openssl_error_string-Beispiel
  • Example#931 - openssl_get_cert_locations example
  • Example#932 - openssl_get_cipher_methods example
  • Example#933 - openssl_get_curve_names example
  • Example#934 - openssl_get_md_methods example
  • Example#935 - openssl_open-Beispiel
  • Example#936 - openssl_pbkdf2() example
  • Example#937 - openssl_pkcs12_read-Beispiel
  • Example#938 - openssl_pkcs7_decrypt-Beispiel
  • Example#939 - openssl_pkcs7_encrypt-Beispiel
  • Example#940 - Get a PEM array from a P7B file
  • Example#941 - openssl_pkcs7_sign-Beispiel
  • Example#942 - openssl_pkey_derive example
  • Example#943 - Aus einem privaten Schlüssel den öffentlichen Schlüssel gewinnen
  • Example#944 - openssl_random_pseudo_bytes example
  • Example#945 - openssl_seal-Beispiel
  • Example#946 - openssl_sign-Beispiel
  • Example#947 - openssl_sign-Beispiel
  • Example#948 - openssl_spki_export_challenge example
  • Example#949 - openssl_spki_export_challenge example from <keygen>
  • Example#950 - openssl_spki_export example
  • Example#951 - openssl_spki_export example from <keygen>
  • Example#952 - openssl_spki_new example
  • Example#953 - openssl_spki_verify example
  • Example#954 - openssl_spki_verify example from <keygen>
  • Example#955 - openssl_verify-Beispiel
  • Example#956 - openssl_verify-Beispiel
  • Example#957 - openssl_x509_verify example
  • Example#958 - Basic password usage
  • Example#959 - password_hash-Beispiel
  • Example#960 - password_hash-Beispiel mit manuell festgelegten Kosten
  • Example#961 - password_hash-Beispiel für die Suche nach angemessenen Kosten
  • Example#962 - password_hash-Beispiel, das Argon2i verwendet
  • Example#963 - Die Verwendung von password_needs_rehash
  • Example#964 - password_verify-Beispiel
  • Example#965 - RNP clearsign example
  • Example#966 - simple callback function example
  • Example#967 - sodium_crypto_box_seal_open example
  • Example#968 - sodium_crypto_box_seal example
  • Example#969 - sodium_crypto_core_ristretto255_add example
  • Example#970 - sodium_crypto_core_ristretto255_from_hash example
  • Example#971 - sodium_crypto_core_ristretto255_is_valid_point example
  • Example#972 - sodium_crypto_core_ristretto255_random example
  • Example#973 - sodium_crypto_core_ristretto255_scalar_add example
  • Example#974 - sodium_crypto_core_ristretto255_scalar_invert example
  • Example#975 - sodium_crypto_core_ristretto255_scalar_negate example
  • Example#976 - sodium_crypto_core_ristretto255_scalar_random example
  • Example#977 - sodium_crypto_core_ristretto255_scalar_sub example
  • Example#978 - sodium_crypto_core_ristretto255_sub example
  • Example#979 - sodium_crypto_generichash_final example
  • Example#980 - sodium_crypto_generichash_init example
  • Example#981 - sodium_crypto_generichash_update example
  • Example#982 - sodium_crypto_kx_keypair usage
  • Example#983 - sodium_crypto_pwhash_str example
  • Example#984 - sodium_crypto_pwhash example
  • Example#985 - sodium_crypto_secretbox_keygen example
  • Example#986 - Comparing sodium_crypto_secretbox_keygen with random_bytes
  • Example#987 - sodium_crypto_secretbox_open example
  • Example#988 - sodium_crypto_secretbox example
  • Example#989 - sodium_crypto_secretstream_xchacha20poly1305_init_pull example
  • Example#990 - sodium_crypto_secretstream_xchacha20poly1305_init_push example
  • Example#991 - sodium_crypto_stream_xchacha20_xor_ic example
  • Example#992 - DBA Beispiel
  • Example#993 - Durchlaufen einer Datenbank
  • Example#994 - dba_handlers-Beispiel
  • Example#995 - Zugriffsberechtigungen für eine Spalte auflisten
  • Example#996 - List Columns of a Table
  • Example#997 - DSN-lose Verbindung
  • Example#998 - odbc_connection_string_quote example
  • Example#999 - List available DSNs
  • Example#1000 - Beispiel für odbc_execute und odbc_prepare
  • Example#1001 - odbc_fetch_into-Beispiele
  • Example#1002 - odbc_next_result
  • Example#1003 - Beispiel für odbc_execute und odbc_prepare
  • Example#1004 - List primary Keys of a Column
  • Example#1005 - List Columns of a stored Procedure
  • Example#1006 - List stored Procedures of a Database
  • Example#1007 - odbc_result-Beispiele
  • Example#1008 - odbc_setoption-Beispiele
  • Example#1009 - List Statistics of a Table
  • Example#1010 - List Privileges of a Table
  • Example#1011 - List Tables in a Catalog
  • Example#1012 - Die Verwendung von PDO::ATTR_DRIVER_NAME
  • Example#1013 - Mit MySQL verbinden
  • Example#1014 - Verbindungsfehler behandeln
  • Example#1015 - Eine Verbindung schließen
  • Example#1016 - Persistente Verbindungen
  • Example#1017 - Mehrere Abfragen in einer Transaktion
  • Example#1018 - Wiederholte Inserts mit Prepared Statements
  • Example#1019 - Wiederholte Inserts mit Prepared Statements
  • Example#1020 - Abfragen von Daten mit Prepared Statements
  • Example#1021 - Eine Stored Procedure mit einem Ausgabeparameter aufrufen
  • Example#1022 - Eine Stored Procedure mit einem Eingabe-/Ausgabe-Parameter aufrufen
  • Example#1023 - Ungültige Verwendung von Platzhaltern
  • Example#1024 - Eine PDO Instanz erstellen und die Fehlermethode setzen
  • Example#1025 - Erzeugen eines PDO-Exemplars und setzen der Fehlermethode per Konstruktor
  • Example#1026 - Ein Bild aus einer Datenbank anzeigen
  • Example#1027 - Ein Bild in eine Datenbank einfügen
  • Example#1028 - Ein Bild in eine Datenbank einfügen: Oracle
  • Example#1029 - Rückgängigmachen (Rollback) einer Transaktion
  • Example#1030 - Bestätigen einer gewöhnlichen Transaktion
  • Example#1031 - Bestätigen einer DDL-Transaktion
  • Example#1032 - Erstellen einer PDO-Instanz über den Aufruf eines Treibers
  • Example#1033 - Erstellen einer PDO-Instanz über den Aufruf eines URIs
  • Example#1034 - Erstellen einer PDO-Instanz über einen Alias
  • Example#1035 - Abrufen eines SQLSTATE-Codes
  • Example#1036 - Anzeigen der errorInfo()-Felder einer PDO_ODBC-Verbindung zu einer DB2-Datenbank
  • Example#1037 - Ein DELETE-Statement ausführen
  • Example#1038 - Abrufen von Attributen der Datenbankverbindung
  • Example#1039 - PDO::getAvailableDrivers-Beispiel
  • Example#1040 - Vorlage für eine SQL-Anweisung mit benannten Parametern
  • Example#1041 - Vorlage für eine SQL-Anweisung mit Fragezeichen als Platzhalter
  • Example#1042 - Vorlage für eine SQL-Anweisung mit maskierten Fragezeichen
  • Example#1043 - SQL ohne Platzhalter kann mit PDO::query ausgeführt werden
  • Example#1044 - Schützen einer normalen Zeichenkette
  • Example#1045 - Schützen einer gefährlichen Zeichenkette
  • Example#1046 - Schützen einer komplexen Zeichenkette
  • Example#1047 - Rückgängigmachen einer Transaktion
  • Example#1048 - Binden der Ergebnismenge an PHP-Variablen
  • Example#1049 - Ausführen einer vorbereiteten Anweisung mit benannten Platzhaltern
  • Example#1050 - Ausführen einer vorbereiteten Anweisung mit Fragezeichen-Platzhaltern
  • Example#1051 - Aufrufen einer gespeicherten Prozedur mit einem INOUT-Parameter
  • Example#1052 - Ausführen einer vorbereiteten Anweisung mit benannten Platzhaltern
  • Example#1053 - Ausführen einer vorbereiteten Anweisung mit Fragezeichen-Platzhaltern
  • Example#1054 - PDOStatement::closeCursor-Beispiel
  • Example#1055 - Zählen der Spalten
  • Example#1056 - PDOStatement::debugDumpParams-Beispiel mit benannten Parametern
  • Example#1057 - PDOStatement::debugDumpParams-Beispiel mit Fragezeichen-Parametern
  • Example#1058 - Abrufen eines SQLSTATE-Codes
  • Example#1059 - Anzeigen der errorInfo()-Felder einer PDO_ODBC-Verbindung zu einer DB2-Datenbank
  • Example#1060 - Ein Prepared Statement mit Variablen- und Wertebindung ausführen
  • Example#1061 - Ein Prepared Statement mit einem Array von benannten Eingabewerten ausführen
  • Example#1062 - Ein Prepared Statement mit einem Array von Positionswerten ausführen
  • Example#1063 - Ein Prepared Statement mit Variablen ausführen, die an positionale Platzhalter gebunden sind
  • Example#1064 - Ein Prepared Statement mit einem Array für eine IN-Klausel ausführen
  • Example#1065 - Abrufen von Zeilen mit verschiedenen Arten des Abrufs
  • Example#1066 - Abrufen von Zeilen mittels scrollbarem Cursor
  • Example#1067 - Reihenfolge der Konstruktion
  • Example#1068 - Abrufen der restlichen Zeilen einer Ergebnismenge
  • Example#1069 - Abrufen aller Werte einer einzelnen Spalte einer Ergebnismenge
  • Example#1070 - Gruppieren aller Werte nach einer einzelnen Spalte
  • Example#1071 - Instanziieren einer Klasse für jedes Ergebnis
  • Example#1072 - Aufrufen einer Funktion für jedes Ergebnis
  • Example#1073 - Abrufen der ersten Spalte aus der nächsten Zeile
  • Example#1074 - Abrufen der Metadaten einer Spalte
  • Example#1075 - Abrufen mehrerer von einer gespeicherten Prozedur zurückgegebener Zeilensätze
  • Example#1076 - Ermitteln der Anzahl der gelöschten Zeilen
  • Example#1077 - Zählen der Zeilen, die von einer SELECT-Anweisung zurückgegeben wurden
  • Example#1078 - Festlegen des Abrufmodus
  • Example#1079 - Insert LOBs in CUBRID PDO
  • Example#1080 - Fetch LOBs in CUBRID PDO
  • Example#1081 - Insert set in CUBRID PDO with default data type.
  • Example#1082 - Specify data type when insert set in CUBRID PDO
  • Example#1083 - PDO_CUBRID DSN examples
  • Example#1084 - A PDO::cubrid_schema example
  • Example#1085 - PDO_DBLIB DSN examples
  • Example#1086 - PDO_FIREBIRD DSN example with path
  • Example#1087 - PDO_FIREBIRD DSN example with port and path
  • Example#1088 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1089 - PDO_FIREBIRD DSN to connect to a dialect 1 database
  • Example#1090 - PDO_IBM DSN example using db2cli.ini
  • Example#1091 - PDO_IBM DSN example using a connection string
  • Example#1092 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1093 - PDO_INFORMIX DSN example using a connection string
  • Example#1094 - Den ungepufferten Modus von MySQL aktivieren
  • Example#1095 - DSN-Beispiele für PDO_MYSQL
  • Example#1096 - PDO_SQLSRV DSN examples
  • Example#1097 - PDO_OCI DSN examples
  • Example#1098 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1099 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1100 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1101 - PDO_PGSQL DSN examples
  • Example#1102 - A PDO::pgsqlLOBCreate example
  • Example#1103 - A PDO::pgsqlLOBOpen example
  • Example#1104 - A PDO::pgsqlLOBUnlink example
  • Example#1105 - PDO_SQLITE DSN Beispiele
  • Example#1106 - Beispiel für eine 'max_length'-Aggregationsfunktion
  • Example#1107 - PDO::sqliteCreateCollation example
  • Example#1108 - PDO::sqliteCreateFunction-Beispiel
  • Example#1109 - Example of Data Retrieval
  • Example#1110 - Example of Data Insertion
  • Example#1111 - cubrid_bind example
  • Example#1112 - cubrid_bind BLOB/CLOB example
  • Example#1113 - cubrid_bind BLOB/CLOB example
  • Example#1114 - cubrid_close_prepare example
  • Example#1115 - cubrid_close_request example
  • Example#1116 - cubrid_col_get example
  • Example#1117 - cubrid_col_size example
  • Example#1118 - cubrid_column_names example
  • Example#1119 - cubrid_column_types example
  • Example#1120 - cubrid_commit example
  • Example#1121 - cubrid_connect_with_url url without properties example
  • Example#1122 - cubrid_connect_with_url url with properties example
  • Example#1123 - cubrid_connect example
  • Example#1124 - cubrid_current_oid example
  • Example#1125 - cubrid_disconnect example
  • Example#1126 - cubrid_drop example
  • Example#1127 - cubrid_error_code_facility example
  • Example#1128 - cubrid_error_code example
  • Example#1129 - cubrid_error_msg example
  • Example#1130 - cubrid_execute example
  • Example#1131 - cubrid_fetch example
  • Example#1132 - cubrid_free_result example
  • Example#1133 - cubrid_get_charset example
  • Example#1134 - cubrid_get_class_name example
  • Example#1135 - cubrid_get_client_info example
  • Example#1136 - cubrid_get_db_parameter example
  • Example#1137 - cubrid_get_query_timeout example
  • Example#1138 - cubrid_get_server_info example
  • Example#1139 - cubrid_get example
  • Example#1140 - cubrid_insert_id example
  • Example#1141 - cubrid_is_instance example
  • Example#1142 - cubrid_lob_close example
  • Example#1143 - cubrid_lob_export example
  • Example#1144 - cubrid_lob_get example
  • Example#1145 - cubrid_lob_send example
  • Example#1146 - cubrid_lob_size example
  • Example#1147 - cubrid_lob2_bind example
  • Example#1148 - cubrid_lob2_export example
  • Example#1149 - cubrid_lob2_export example
  • Example#1150 - cubrid_lob2_read example 1
  • Example#1151 - cubrid_lob2_read example 2
  • Example#1152 - cubrid_lob2_seek64 example
  • Example#1153 - cubrid_lob2_seek example
  • Example#1154 - cubrid_lob2_write example 1
  • Example#1155 - cubrid_lob2_write example 2
  • Example#1156 - cubrid_lock_read example
  • Example#1157 - cubrid_lock_write example
  • Example#1158 - cubrid_move_cursor example
  • Example#1159 - cubrid_next_result example
  • Example#1160 - cubrid_num_cols example
  • Example#1161 - cubrid_num_rows example
  • Example#1162 - cubrid_pconnect_with_url url without properties example
  • Example#1163 - cubrid_pconnect_with_url url with properties example
  • Example#1164 - cubrid_connect example
  • Example#1165 - cubrid_prepare example
  • Example#1166 - cubrid_put example
  • Example#1167 - cubrid_rollback example
  • Example#1168 - cubrid_schema example
  • Example#1169 - cubrid_seq_drop example
  • Example#1170 - cubrid_seq_insert example
  • Example#1171 - cubrid_seq_put example
  • Example#1172 - cubrid_set_add example
  • Example#1173 - cubrid_get_db_parameter example
  • Example#1174 - cubrid_set_drop example
  • Example#1175 - cubrid_version example
  • Example#1176 - cubrid_affected_rows example
  • Example#1177 - cubrid_client_encoding example
  • Example#1178 - cubrid_close example
  • Example#1179 - cubrid_data_seek example
  • Example#1180 - cubrid_db_name example
  • Example#1181 - cubrid_errno example
  • Example#1182 - cubrid_error example
  • Example#1183 - cubrid_fetch_array example
  • Example#1184 - cubrid_fetch_assoc example
  • Example#1185 - cubrid_fetch_field example
  • Example#1186 - cubrid_fetch_lengths example
  • Example#1187 - cubrid_fetch_object example
  • Example#1188 - cubrid_fetch_row example
  • Example#1189 - cubrid_field_flags example
  • Example#1190 - cubrid_field_len example
  • Example#1191 - cubrid_field_name example
  • Example#1192 - cubrid_field_seek example
  • Example#1193 - cubrid_field_table example
  • Example#1194 - cubrid_field_type example
  • Example#1195 - cubrid_list_dbs example
  • Example#1196 - cubrid_num_fields example
  • Example#1197 - cubrid_ping example
  • Example#1198 - Invalid Query
  • Example#1199 - Valid Query
  • Example#1200 - cubrid_real_escape_string example
  • Example#1201 - cubrid_result example
  • Example#1202 - cubrid_unbuffered_query example
  • Example#1203 - cubrid_load_from_glo example
  • Example#1204 - cubrid_new_glo example
  • Example#1205 - cubrid_save_to_glo example
  • Example#1206 - cubrid_send_glo example
  • Example#1207 - Einen Datensatz in eine dBase-Datenbank einfügen
  • Example#1208 - Schließen einer dBase-Datenbankdatei
  • Example#1209 - Erzeugen einer dBase-Datenbankdatei
  • Example#1210 - Anzeigen der Informationen des Dateikopfs einer dBase-Datenbankdatei
  • Example#1211 - Liste aller in der Datenbank eingetragener Mitglieder
  • Example#1212 - dbase_numfields-Beispiel
  • Example#1213 - Eine Schleife über alle Datensätze der Datenbank ausführen
  • Example#1214 - Öffnen einer dBase-Datenbankdatei
  • Example#1215 - Leeren einer dBase-Datenbank
  • Example#1216 - Aktualisieren eines Datensatzes in der Datenbank
  • Example#1217 - ibase_backup-Beispiel
  • Example#1218 - ibase_backup-Beispiel mit Argumenten
  • Example#1219 - ibase_blob_get-Beispiel
  • Example#1220 - ibase_blob_import-Beispiel
  • Example#1221 - ibase_connect-Beispiel:
  • Example#1222 - ibase_execute-Beispiel
  • Example#1223 - ibase_fetch_object example
  • Example#1224 - ibase_field_info-Beispiel
  • Example#1225 - ibase_name_result-Beispiel
  • Example#1226 - ibase_num_fields Beispiel
  • Example#1227 - ibase_query example
  • Example#1228 - ibase_restore-Beispiel
  • Example#1229 - ibase_restore-Beispiel mit Argumenten
  • Example#1230 - ibase_service_attach-Beispiel
  • Example#1231 - ibase_service_attach-Beispiel
  • Example#1232 - ibase_service_attach-Beispiel mit hostname/port-Syntax
  • Example#1233 - ibase_service_detach-Beispiel
  • Example#1234 - ibase_set_event_handler-Beispiel
  • Example#1235 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1236 - Setting the AUTOCOMMIT value for a connection
  • Example#1237 - Binding PHP variables to a prepared statement
  • Example#1238 - Calling stored procedures with IN and OUT parameters
  • Example#1239 - Inserting a binary large object (BLOB) directly from a file
  • Example#1240 - A db2_client_info example
  • Example#1241 - Closing a connection
  • Example#1242 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1243 - Retrieving the error message returned by a failed connection attempt
  • Example#1244 - Creating a cataloged connection
  • Example#1245 - Creating an uncataloged connection
  • Example#1246 - Creating a connection with autocommit off by default
  • Example#1247 - i5/OS best performance
  • Example#1248 - Using trusted context
  • Example#1249 - A db2_escape_string example
  • Example#1250 - Creating a table with db2_exec
  • Example#1251 - Executing a SELECT statement with a scrollable cursor
  • Example#1252 - Returning XML data as an SQL ResultSet
  • Example#1253 - Performing a "JOIN" with XML data
  • Example#1254 - Returning SQL data as part of a larger XML document
  • Example#1255 - Preparing and executing an SQL statement with parameter markers
  • Example#1256 - Calling a stored procedure with an OUT parameter
  • Example#1257 - Returning XML data as an SQL ResultSet
  • Example#1258 - Performing a "JOIN" with XML data
  • Example#1259 - Returning SQL data as part of a larger XML document
  • Example#1260 - Iterating through a forward-only cursor
  • Example#1261 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1262 - Iterating through a forward-only cursor
  • Example#1263 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1264 - Iterating through a forward-only cursor
  • Example#1265 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1266 - A db2_fetch_object example
  • Example#1267 - Iterating through a result set
  • Example#1268 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1269 - Setting and retrieving parameters through a connection resource
  • Example#1270 - A db2_last_insert_id example
  • Example#1271 - Iterating through different types of data
  • Example#1272 - Calling a stored procedure that returns multiple result sets
  • Example#1273 - Retrieving the number of fields in a result set
  • Example#1274 - Closing a persistent connection
  • Example#1275 - A db2_pconnect example
  • Example#1276 - Using trusted context
  • Example#1277 - Preparing and executing an SQL statement with parameter markers
  • Example#1278 - A db2_result example
  • Example#1279 - Rolling back a DELETE statement
  • Example#1280 - A db2_server_info example
  • Example#1281 - Setting one parameter with a connection resource
  • Example#1282 - Setting multiple parameters with a connection resource
  • Example#1283 - Setting multiple parameters with an invalid key
  • Example#1284 - Setting multiple parameters with an invalid value
  • Example#1285 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1286 - Setting multiple parameters with the wrong resource
  • Example#1287 - Putting it all together
  • Example#1288 - i5/OS cursors are read-only
  • Example#1289 - MongoDB\Driver\Manager::__construct basic example
  • Example#1290 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1291 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1292 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1293 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1294 - Limiting execution time for a command
  • Example#1295 - MongoDB\Driver\Manager::executeQuery example
  • Example#1296 - Limiting execution time for a query
  • Example#1297 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1298 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1299 - MongoDB\Driver\Manager::getServers example
  • Example#1300 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1301 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1302 - MongoDB\Driver\Command::__construct example
  • Example#1303 - MongoDB\Driver\Command::__construct example
  • Example#1304 - MongoDB\Driver\Query::__construct example
  • Example#1305 - Mixed write operations are grouped by type
  • Example#1306 - Ordered write operations causing an error
  • Example#1307 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1308 - MongoDB\Driver\BulkWrite::count example
  • Example#1309 - MongoDB\Driver\BulkWrite::delete example
  • Example#1310 - MongoDB\Driver\BulkWrite::insert example
  • Example#1311 - MongoDB\Driver\BulkWrite::update example
  • Example#1312 - Declare an API version on a manager
  • Example#1313 - Declare a strict API version on a manager
  • Example#1314 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1315 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1316 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1317 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1318 - MongoDB\Driver\WriteConcern::getW example
  • Example#1319 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1320 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1321 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1322 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1323 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1324 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1325 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1326 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1327 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1328 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1329 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1330 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1331 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1332 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1333 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1334 - Reading a result set
  • Example#1335 - Reading a result set for a tailable cursor
  • Example#1336 - MongoDB\Driver\Cursor::getId example
  • Example#1337 - MongoDB\Driver\Cursor::getServer example
  • Example#1338 - MongoDB\Driver\Cursor::isDead example
  • Example#1339 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1340 - MongoDB\Driver\Cursor::toArray example
  • Example#1341 - MongoDB\Driver\CursorId::__toString example
  • Example#1342 - MongoDB\Driver\Server::getHost example
  • Example#1343 - MongoDB\Driver\Server::getInfo example
  • Example#1344 - MongoDB\Driver\Server::getLatency example
  • Example#1345 - MongoDB\Driver\Server::getPort example
  • Example#1346 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1347 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1348 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1349 - MongoDB\Driver\WriteError::getCode example
  • Example#1350 - MongoDB\Driver\WriteError::getIndex example
  • Example#1351 - MongoDB\Driver\WriteError::getMessage example
  • Example#1352 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1353 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1354 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1355 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1356 - MongoDB\Driver\WriteResult::getServer example
  • Example#1357 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1358 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1359 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1360 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1361 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1362 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1363 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1364 - MongoDB\BSON\fromJSON example
  • Example#1365 - MongoDB\BSON\fromPHP example
  • Example#1366 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1367 - MongoDB\BSON\toJSON example
  • Example#1368 - MongoDB\BSON\toPHP example
  • Example#1369 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1370 - MongoDB\BSON\Document::toCanonicalExtendedJSON example
  • Example#1371 - MongoDB\BSON\Document::toRelaxedExtendedJSON example
  • Example#1372 - MongoDB\BSON\Binary::__construct example
  • Example#1373 - MongoDB\BSON\Binary::getData example
  • Example#1374 - MongoDB\BSON\Binary::getType example
  • Example#1375 - MongoDB\BSON\Binary::__toString example
  • Example#1376 - MongoDB\BSON\Decimal128::__construct example
  • Example#1377 - MongoDB\BSON\Decimal128::__toString example
  • Example#1378 - MongoDB\BSON\Javascript::__construct example
  • Example#1379 - MongoDB\BSON\Javascript::getCode example
  • Example#1380 - MongoDB\BSON\Javascript::getScope example
  • Example#1381 - MongoDB\BSON\Javascript::__toString example
  • Example#1382 - MongoDB\BSON\MaxKey::__construct example
  • Example#1383 - MongoDB\BSON\MinKey::__construct example
  • Example#1384 - MongoDB\BSON\ObjectId::__construct example
  • Example#1385 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1386 - MongoDB\BSON\ObjectId::__toString example
  • Example#1387 - MongoDB\BSON\Regex::__construct example
  • Example#1388 - MongoDB\BSON\Regex::getFlags example
  • Example#1389 - MongoDB\BSON\Regex::getPattern example
  • Example#1390 - MongoDB\BSON\Regex::__toString example
  • Example#1391 - MongoDB\BSON\Timestamp::__construct example
  • Example#1392 - MongoDB\BSON\Timestamp::__toString example
  • Example#1393 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1394 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1395 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1396 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1397 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1398 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1399 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1400 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1401 - MongoDB\BSON\Int64::__toString example
  • Example#1402 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1403 - Vergleich der MySQL-APIs
  • Example#1404 - Vergleich mit vorbereiteten Anweisungen
  • Example#1405 - Konfigurationsoptionen für die Verwendung von mysqlnd oder libmysqlclient
  • Example#1406 - Beispiel für ungepufferte Abfragen: mysqli
  • Example#1407 - Beispiel für ungepufferte Abfragen: pdo_mysql
  • Example#1408 - Probleme beim Einstellen des Zeichensatzes mit SQL
  • Example#1409 - Beispiel für das Einstellen des Zeichensatzes: mysqli
  • Example#1410 - Beispiel für das Einstellen des Zeichensatzes: pdo_mysql
  • Example#1411 - Einfacher Umstieg von der alten mysql-Erweiterung
  • Example#1412 - Objektorientierte und prozedurale Schnittstelle
  • Example#1413 - Schlechter Programmierstil
  • Example#1414 - Die besondere Bedeutung von localhost
  • Example#1415 - Standardwerte festlegen
  • Example#1416 - Ausführen von Anfragen
  • Example#1417 - Navigation durch gepufferte Ergebnisse
  • Example#1418 - Navigation durch ungepufferte Ergebnisse
  • Example#1419 - Das Textprotokoll gibt standardmäßig Zeichenketten zurück
  • Example#1420 - Native Datentypen bei mysqlnd und Verbindungsoption
  • Example#1421 - Vorbereitete Anweisung
  • Example#1422 - INSERT einmal vorbereitet, mehrfach ausgeführt
  • Example#1423 - Weniger Umläufe durch multi-INSERT-SQL
  • Example#1424 - Native Datentypen
  • Example#1425 - Binden der Ausgabevariablen
  • Example#1426 - Verwendung von mysqli_result zum Abrufen von Ergebnissen
  • Example#1427 - Gepufferte Ergebnismenge für flexibles Auslesen
  • Example#1428 - Aufrufen einer gespeicherten Prozedur
  • Example#1429 - Verwendung von Session-Variablen
  • Example#1430 - Ergebnisse von gespeicherten Prozeduren abrufen
  • Example#1431 - Gespeicherte Prozeduren und vorbereitete Anweisungen
  • Example#1432 - Gespeicherte Prozeduren und vorbereitete Anweisungen mit der bind-API
  • Example#1433 - Mehrere Anweisungen
  • Example#1434 - SQL-Injection
  • Example#1435 - Einstellen des autocommit-Modus mit SQL und über die API
  • Example#1436 - Übertragen und Zurücksetzen (Commit und Rollback)
  • Example#1437 - Zugriff auf die Metadaten der Ergebnismenge
  • Example#1438 - Metadaten der vorbereiteten Anweisungen
  • Example#1439 - $mysqli->affected_rows-Beispiel
  • Example#1440 - mysqli::autocommit-Beispiel
  • Example#1441 - mysqli::begin_transaction-Beispiel
  • Example#1442 - mysqli::change_user-Beispiel
  • Example#1443 - mysqli::character_set_name-Beispiel
  • Example#1444 - mysqli::close-Beispiel
  • Example#1445 - $mysqli->connect_errno-Beispiel
  • Example#1446 - $mysqli->connect_error-Beispiel
  • Example#1447 - mysqli::__construct-Beispiel
  • Example#1448 - Erweitern der Klasse mysqli
  • Example#1449 - Manuelle Fehlerbehandlung
  • Example#1450 - Erzeugen einer Trace-Datei
  • Example#1451 - $mysqli->errno-Beispiel
  • Example#1452 - $mysqli->error_list-Beispiel
  • Example#1453 - $mysqli->error-Beispiel
  • Example#1454 - mysqli::execute_query-Beispiel
  • Example#1455 - $mysqli->field_count-Beispiel
  • Example#1456 - mysqli::get_charset-Beispiel
  • Example#1457 - mysqli_get_client_info
  • Example#1458 - mysqli_get_client_version
  • Example#1459 - mysqli_get_connection_stats-Beispiel
  • Example#1460 - $mysqli->host_info-Beispiel
  • Example#1461 - $mysqli->protocol_version-Beispiel
  • Example#1462 - $mysqli->server_info-Beispiel
  • Example#1463 - $mysqli->server_version-Beispiel
  • Example#1464 - $mysqli->info-Beispiel
  • Example#1465 - $mysqli->insert_id-Beispiel
  • Example#1466 - mysqli::kill-Beispiel
  • Example#1467 - mysqli::multi_query-Beispiel
  • Example#1468 - mysqli::ping-Beispiel
  • Example#1469 - mysqli_poll-Beispiel
  • Example#1470 - mysqli::prepare-Beispiel
  • Example#1471 - mysqli::query-Beispiel
  • Example#1472 - mysqli::real_connect-Beispiel
  • Example#1473 - mysqli::real_escape_string-Beispiel
  • Example#1474 - mysqli::select_db-Beispiel
  • Example#1475 - mysqli::set_charset-Beispiel
  • Example#1476 - $mysqli->sqlstate-Beispiel
  • Example#1477 - mysqli::stat-Beispiel
  • Example#1478 - $mysqli->thread_id-Beispiel
  • Example#1479 - mysqli::use_result-Beispiel
  • Example#1480 - $mysqli->warning_count-Beispiel
  • Example#1481 - mysqli_stmt_affected_rows-Beispiel
  • Example#1482 - mysqli_stmt::bind_param-Beispiel
  • Example#1483 - Argumente mittels ... übergeben
  • Example#1484 - Objektorientierter Stil
  • Example#1485 - Prozeduraler Stil
  • Example#1486 - Objektorientierter Stil
  • Example#1487 - Prozeduraler Stil
  • Example#1488 - Objektorientierter Stil
  • Example#1489 - Prozeduraler Stil
  • Example#1490 - Objektorientierter Stil
  • Example#1491 - Prozeduraler Stil
  • Example#1492 - Objektorientierter Stil
  • Example#1493 - Prozeduraler Stil
  • Example#1494 - Ausführen einer vorbereiteten Anweisung mit gebundenen Variablen
  • Example#1495 - Ausführen einer vorbereiteten Anweisung mit einem Array von Werten
  • Example#1496 - Objektorientierter Stil
  • Example#1497 - Prozeduraler Stil
  • Example#1498 - Objektorientierter Stil
  • Example#1499 - Prozeduraler Stil
  • Example#1500 - Objektorientierter Stil
  • Example#1501 - Prozeduraler Stil
  • Example#1502 - Objektorientierter Stil
  • Example#1503 - Prozeduraler Stil
  • Example#1504 - Objektorientierter Stil
  • Example#1505 - Prozeduraler Stil
  • Example#1506 - mysqli_stmt::prepare-Beispiel
  • Example#1507 - Objektorientierter Stil
  • Example#1508 - Prozeduraler Stil
  • Example#1509 - Objektorientierter Stil
  • Example#1510 - Objektorientierter Stil
  • Example#1511 - Prozeduraler Stil
  • Example#1512 - Objektorientierter Stil
  • Example#1513 - Prozeduraler Stil
  • Example#1514 - Erstellen eines mysqli_result-Objekts
  • Example#1515 - Objektorientierter Stil
  • Example#1516 - Prozeduraler Stil
  • Example#1517 - mysqli::data_seek-Beispiel
  • Example#1518 - Anpassen des Ergebniszeigers beim Iterieren
  • Example#1519 - mysqli_result::fetch_all-Beispiel
  • Example#1520 - mysqli_result::fetch_array-Beispiel
  • Example#1521 - mysqli_result::fetch_assoc-Beispiel
  • Example#1522 - Vergleich der Verwendung von mysqli_result iterator und mysqli_result::fetch_assoc
  • Example#1523 - mysqli_result::fetch_column-Beispiel
  • Example#1524 - Objektorientierter Stil
  • Example#1525 - Prozeduraler Stil
  • Example#1526 - Objektorientierter Stil
  • Example#1527 - Prozeduraler Stil
  • Example#1528 - Objektorientierter Stil
  • Example#1529 - Prozeduraler Stil
  • Example#1530 - mysqli_result::fetch_object-Beispiel
  • Example#1531 - mysqli_result::fetch_row-Beispiel
  • Example#1532 - Objektorientierter Stil
  • Example#1533 - Prozeduraler Stil
  • Example#1534 - Objektorientierter Stil
  • Example#1535 - Prozeduraler Stil
  • Example#1536 - Objektorientierter Stil
  • Example#1537 - Prozeduraler Stil
  • Example#1538 - Objektorientierter Stil
  • Example#1539 - Prozeduraler Stil
  • Example#1540 - Objektorientierter Stil
  • Example#1541 - Prozeduraler Stil
  • Example#1542 - Nur Fehler melden, die sich nicht auf den Index beziehen
  • Example#1543 - mysqli_get_client_stats-Beispiel
  • Example#1544 - Verbindung zu einem MySQL-Server aufbauen
  • Example#1545 - Erstellen eines Schemas und einer Sammlung auf dem MySQL-Server
  • Example#1546 - Speichern und Abrufen von Daten
  • Example#1547 - Abrufen und Durchlaufen mehrerer Dokumente
  • Example#1548 - mysql_xdevapi\Expression-Beispiel
  • Example#1549 - Beispiele für URIs
  • Example#1550 - mysql_xdevapi\getSession-Beispiel
  • Example#1551 - mysql_xdevapi\RowResult::getWarnings-Beispiel
  • Example#1552 - mysql_xdevapi\RowResult::getWarningsCount-Beispiel
  • Example#1553 - mysql_xdevapi\Client::__construct-Beispiel
  • Example#1554 - mysql_xdevapi\Collection::add-Beispiel
  • Example#1555 - mysql_xdevapi\Collection::addOrReplaceOne-Beispiel
  • Example#1556 - mysql_xdevapi\Collection::getOne-Beispiel
  • Example#1557 - mysql_xdevapi\Collection::count-Beispiel
  • Example#1558 - mysql_xdevapi\Collection::createIndex-Beispiel
  • Example#1559 - mysql_xdevapi\Collection::dropIndex-Beispiel
  • Example#1560 - mysql_xdevapi\Collection::existsInDatabase-Beispiel
  • Example#1561 - mysql_xdevapi\Collection::find-Beispiel
  • Example#1562 - mysql_xdevapi\Collection::getName-Beispiel
  • Example#1563 - mysql_xdevapi\Collection::getOne-Beispiel
  • Example#1564 - mysql_xdevapi\Collection::getSchema-Beispiel
  • Example#1565 - mysql_xdevapi\Collection::getSession-Beispiel
  • Example#1566 - mysql_xdevapi\Collection::modify-Beispiel
  • Example#1567 - mysql_xdevapi\Collection::remove-Beispiel
  • Example#1568 - mysql_xdevapi\Collection::removeOne-Beispiel
  • Example#1569 - mysql_xdevapi\Collection::replaceOne-Beispiel
  • Example#1570 - mysql_xdevapi\CollectionAdd::__construct-Beispiel
  • Example#1571 - mysql_xdevapi\CollectionAdd::execute-Beispiel
  • Example#1572 - mysql_xdevapi\CollectionFind::bind-Beispiel
  • Example#1573 - CollectionFind-Beispiel
  • Example#1574 - CollectionFind-Beispiel
  • Example#1575 - mysql_xdevapi\CollectionFind::fields-Beispiel
  • Example#1576 - mysql_xdevapi\CollectionFind::groupBy-Beispiel
  • Example#1577 - mysql_xdevapi\CollectionFind::having-Beispiel
  • Example#1578 - mysql_xdevapi\CollectionFind::limit-Beispiel
  • Example#1579 - mysql_xdevapi\CollectionFind::lockExclusive-Beispiel
  • Example#1580 - mysql_xdevapi\CollectionFind::lockShared-Beispiel
  • Example#1581 - mysql_xdevapi\CollectionFind::offset-Beispiel
  • Example#1582 - mysql_xdevapi\CollectionFind::sort-Beispiel
  • Example#1583 - mysql_xdevapi\CollectionModify::arrayAppend-Beispiel
  • Example#1584 - mysql_xdevapi\CollectionModify::arrayInsert-Beispiel
  • Example#1585 - mysql_xdevapi\CollectionModify::bind-Beispiel
  • Example#1586 - mysql_xdevapi\CollectionModify::__construct-Beispiel
  • Example#1587 - mysql_xdevapi\CollectionModify::execute-Beispiel
  • Example#1588 - mysql_xdevapi\CollectionModify::limit-Beispiel
  • Example#1589 - mysql_xdevapi\CollectionModify::patch-Beispiel
  • Example#1590 - mysql_xdevapi\CollectionModify::replace-Beispiel
  • Example#1591 - mysql_xdevapi\CollectionModify::set-Beispiel
  • Example#1592 - mysql_xdevapi\CollectionModify::skip-Beispiel
  • Example#1593 - mysql_xdevapi\CollectionModify::sort-Beispiel
  • Example#1594 - mysql_xdevapi\CollectionModify::unset-Beispiel
  • Example#1595 - mysql_xdevapi\CollectionRemove::bind-Beispiel
  • Example#1596 - mysql_xdevapi\Collection::remove-Beispiel
  • Example#1597 - mysql_xdevapi\CollectionRemove::execute-Beispiel
  • Example#1598 - mysql_xdevapi\CollectionRemove::limit-Beispiel
  • Example#1599 - mysql_xdevapi\CollectionRemove::sort-Beispiel
  • Example#1600 - mysql_xdevapi\ColumnResult::__construct-Beispiel
  • Example#1601 - mysql_xdevapi\ColumnResult::getCharacterSetName-Beispiel
  • Example#1602 - mysql_xdevapi\ColumnResult::getCollationName-Beispiel
  • Example#1603 - mysql_xdevapi\ColumnResult::getColumnLabel-Beispiel
  • Example#1604 - mysql_xdevapi\ColumnResult::getColumnName-Beispiel
  • Example#1605 - mysql_xdevapi\ColumnResult::getFractionalDigits-Beispiel
  • Example#1606 - mysql_xdevapi\ColumnResult::getLength-Beispiel
  • Example#1607 - mysql_xdevapi\ColumnResult::getSchemaName-Beispiel
  • Example#1608 - mysql_xdevapi\ColumnResult::getTableLabel-Beispiel
  • Example#1609 - mysql_xdevapi\ColumnResult::getTableName-Beispiel
  • Example#1610 - mysql_xdevapi\ColumnResult::getType-Beispiel
  • Example#1611 - mysql_xdevapi\ColumnResult::isNumberSigned-Beispiel
  • Example#1612 - mysql_xdevapi\ColumnResult::isPadded-Beispiel
  • Example#1613 - mysql_xdevapi\CrudOperationBindable::bind-Beispiel
  • Example#1614 - mysql_xdevapi\CrudOperationLimitable::limit-Beispiel
  • Example#1615 - mysql_xdevapi\CrudOperationSkippable::skip-Beispiel
  • Example#1616 - mysql_xdevapi\CrudOperationSortable::sort-Beispiel
  • Example#1617 - mysql_xdevapi\DatabaseObject::existsInDatabase-Beispiel
  • Example#1618 - mysql_xdevapi\DatabaseObject::getName-Beispiel
  • Example#1619 - mysql_xdevapi\DatabaseObject::getSession-Beispiel
  • Example#1620 - DocResult-Beispiel
  • Example#1621 - mysql_xdevapi\DocResult::fetchAll-Beispiel
  • Example#1622 - mysql_xdevapi\DocResult::fetchOne-Beispiel
  • Example#1623 - mysql_xdevapi\DocResult::getWarnings-Beispiel
  • Example#1624 - mysql_xdevapi\DocResult::getWarningsCount-Beispiel
  • Example#1625 - execute()-Beispiele
  • Example#1626 - mysql_xdevapi\ExecutionStatus::__construct-Beispiel
  • Example#1627 - mysql_xdevapi\Expression::__construct-Beispiel
  • Example#1628 - mysql_xdevapi\Result::__construct-Beispiel
  • Example#1629 - mysql_xdevapi\Result::getAffectedItemsCount-Beispiel
  • Example#1630 - mysql_xdevapi\Result::getAutoIncrementValue-Beispiel
  • Example#1631 - mysql_xdevapi\Result::getGeneratedIds-Beispiel
  • Example#1632 - mysql_xdevapi\RowResult::getWarnings-Beispiel
  • Example#1633 - mysql_xdevapi\RowResult::getWarningsCount-Beispiel
  • Example#1634 - mysql_xdevapi\RowResult::__construct-Beispiel
  • Example#1635 - mysql_xdevapi\RowResult::fetchAll-Beispiel
  • Example#1636 - mysql_xdevapi\RowResult::fetchOne-Beispiel
  • Example#1637 - mysql_xdevapi\RowResult::getColumnsCount-Beispiel
  • Example#1638 - mysql_xdevapi\RowResult::getColumnNames-Beispiel
  • Example#1639 - mysql_xdevapi\RowResult::getColumns-Beispiel
  • Example#1640 - mysql_xdevapi\RowResult::getWarnings-Beispiel
  • Example#1641 - mysql_xdevapi\RowResult::getWarningsCount-Beispiel
  • Example#1642 - mysql_xdevapi\Schema::__construct-Beispiel
  • Example#1643 - mysql_xdevapi\Schema::createCollection-Beispiel
  • Example#1644 - Beispiel für die Verwendung von mysql_xdevapi\Schema::createCollection mit Validierungsparameter
  • Example#1645 - mysql_xdevapi\Schema::dropCollection-Beispiel
  • Example#1646 - mysql_xdevapi\Schema::existsInDatabase-Beispiel
  • Example#1647 - mysql_xdevapi\Schema::getCollection-Beispiel
  • Example#1648 - mysql_xdevapi\Schema::getCollectionAsTable-Beispiel
  • Example#1649 - mysql_xdevapi\Schema::getCollections-Beispiel
  • Example#1650 - mysql_xdevapi\Schema::getName-Beispiel
  • Example#1651 - mysql_xdevapi\Schema::getSession-Beispiel
  • Example#1652 - mysql_xdevapi\Schema::getTable-Beispiel
  • Example#1653 - mysql_xdevapi\Schema::getTables-Beispiel
  • Example#1654 - mysql_xdevapi\Session::getSchema-Beispiel
  • Example#1655 - mysql_xdevapi\Session::close-Beispiel
  • Example#1656 - mysql_xdevapi\Session::commit-Beispiel
  • Example#1657 - mysql_xdevapi\Session::__construct-Beispiel
  • Example#1658 - mysql_xdevapi\Session::createSchema-Beispiel
  • Example#1659 - mysql_xdevapi\Session::dropSchema-Beispiel
  • Example#1660 - mysql_xdevapi\Session::generateUuid-Beispiel
  • Example#1661 - mysql_xdevapi\Session::getSchema-Beispiel
  • Example#1662 - mysql_xdevapi\Session::getSchema-Beispiel
  • Example#1663 - mysql_xdevapi\Session::getSchemas-Beispiel
  • Example#1664 - mysql_xdevapi\Session::getServerVersion-Beispiel
  • Example#1665 - mysql_xdevapi\Session::listClients-Beispiel
  • Example#1666 - mysql_xdevapi\Session::quoteName-Beispiel
  • Example#1667 - mysql_xdevapi\Session::releaseSavepoint-Beispiel
  • Example#1668 - mysql_xdevapi\Session::rollback-Beispiel
  • Example#1669 - mysql_xdevapi\Session::rollbackTo-Beispiel
  • Example#1670 - mysql_xdevapi\Session::setSavepoint-Beispiel
  • Example#1671 - mysql_xdevapi\Session::sql-Beispiel
  • Example#1672 - mysql_xdevapi\Session::startTransaction-Beispiel
  • Example#1673 - mysql_xdevapi\SqlStatement::bind-Beispiel
  • Example#1674 - mysql_xdevapi\SqlStatement::__construct-Beispiel
  • Example#1675 - mysql_xdevapi\SqlStatement::execute-Beispiel
  • Example#1676 - mysql_xdevapi\SqlStatement::getNextResult-Beispiel
  • Example#1677 - mysql_xdevapi\SqlStatement::getResult-Beispiel
  • Example#1678 - mysql_xdevapi\SqlStatement::hasMoreResults-Beispiel
  • Example#1679 - mysql_xdevapi\SqlStatementResult::__construct-Beispiel
  • Example#1680 - mysql_xdevapi\SqlStatementResult::fetchAll-Beispiel
  • Example#1681 - mysql_xdevapi\SqlStatementResult::fetchOne-Beispiel
  • Example#1682 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount-Beispiel
  • Example#1683 - mysql_xdevapi\SqlStatementResult::getColumnsCount-Beispiel
  • Example#1684 - mysql_xdevapi\SqlStatementResult::getColumnNames-Beispiel
  • Example#1685 - mysql_xdevapi\SqlStatementResult::getColumns-Beispiel
  • Example#1686 - mysql_xdevapi\SqlStatementResult::getGeneratedIds-Beispiel
  • Example#1687 - mysql_xdevapi\SqlStatementResult::getLastInsertId-Beispiel
  • Example#1688 - mysql_xdevapi\SqlStatementResult::getWarnings-Beispiel
  • Example#1689 - mysql_xdevapi\SqlStatementResult::getWarningsCount-Beispiel
  • Example#1690 - mysql_xdevapi\SqlStatementResult::hasData-Beispiel
  • Example#1691 - mysql_xdevapi\SqlStatementResult::nextResult-Beispiel
  • Example#1692 - mysql_xdevapi\Statement::__construct-Beispiel
  • Example#1693 - mysql_xdevapi\Statement::getNextResult-Beispiel
  • Example#1694 - mysql_xdevapi\Statement::getResult-Beispiel
  • Example#1695 - mysql_xdevapi\Statement::hasMoreResults-Beispiel
  • Example#1696 - mysql_xdevapi\Table::__construct-Beispiel
  • Example#1697 - mysql_xdevapi\Table::count-Beispiel
  • Example#1698 - mysql_xdevapi\Table::delete-Beispiel
  • Example#1699 - mysql_xdevapi\Table::existsInDatabase-Beispiel
  • Example#1700 - mysql_xdevapi\Table::getName-Beispiel
  • Example#1701 - mysql_xdevapi\Table::getSchema-Beispiel
  • Example#1702 - mysql_xdevapi\Table::getSession-Beispiel
  • Example#1703 - mysql_xdevapi\Table::insert-Beispiel
  • Example#1704 - mysql_xdevapi\Table::isView-Beispiel
  • Example#1705 - mysql_xdevapi\Table::count-Beispiel
  • Example#1706 - mysql_xdevapi\Table::update-Beispiel
  • Example#1707 - mysql_xdevapi\TableDelete::bind-Beispiel
  • Example#1708 - mysql_xdevapi\TableDelete::__construct-Beispiel
  • Example#1709 - mysql_xdevapi\TableDelete::execute-Beispiel
  • Example#1710 - mysql_xdevapi\TableDelete::limit-Beispiel
  • Example#1711 - mysql_xdevapi\TableDelete::orderBy-Beispiel
  • Example#1712 - mysql_xdevapi\TableDelete::where-Beispiel
  • Example#1713 - mysql_xdevapi\TableInsert::__construct-Beispiel
  • Example#1714 - mysql_xdevapi\TableInsert::execute-Beispiel
  • Example#1715 - mysql_xdevapi\TableInsert::values-Beispiel
  • Example#1716 - mysql_xdevapi\TableSelect::bind-Beispiel
  • Example#1717 - mysql_xdevapi\TableSelect::__construct-Beispiel
  • Example#1718 - mysql_xdevapi\TableSelect::execute-Beispiel
  • Example#1719 - mysql_xdevapi\TableSelect::groupBy-Beispiel
  • Example#1720 - mysql_xdevapi\TableSelect::having-Beispiel
  • Example#1721 - mysql_xdevapi\TableSelect::limit-Beispiel
  • Example#1722 - mysql_xdevapi\TableSelect::lockExclusive-Beispiel
  • Example#1723 - mysql_xdevapi\TableSelect::lockShared-Beispiel
  • Example#1724 - mysql_xdevapi\TableSelect::offset-Beispiel
  • Example#1725 - mysql_xdevapi\TableSelect::orderBy-Beispiel
  • Example#1726 - mysql_xdevapi\TableSelect::where-Beispiel
  • Example#1727 - mysql_xdevapi\TableUpdate::bind-Beispiel
  • Example#1728 - mysql_xdevapi\TableUpdate::__construct-Beispiel
  • Example#1729 - mysql_xdevapi\TableUpdate::execute-Beispiel
  • Example#1730 - mysql_xdevapi\TableUpdate::limit-Beispiel
  • Example#1731 - mysql_xdevapi\TableUpdate::orderby-Beispiel
  • Example#1732 - mysql_xdevapi\TableUpdate::set-Beispiel
  • Example#1733 - mysql_xdevapi\TableUpdate::where-Beispiel
  • Example#1734 - mysql_xdevapi\Warning::__construct-Beispiel
  • Example#1735 - MySQL-Erweiterung: ein Überblicks-Beispiel
  • Example#1736 - mysql_affected_rows-Beispiel
  • Example#1737 - mysql_affected_rows-Beispiel mit Transaktionen
  • Example#1738 - mysql_client_encoding-Beispiel
  • Example#1739 - mysql_close-Beispiel
  • Example#1740 - mysql_connect-Beispiel
  • Example#1741 - mysql_connect-Beispiel unter Verwendung der hostname:port-Syntax
  • Example#1742 - mysql_connect-Beispiel unter Verwendung der ":/path/to/socket"-Syntax
  • Example#1743 - mysql_create_db-Alternativbeispiel
  • Example#1744 - mysql_data_seek-Beispiel
  • Example#1745 - mysql_db_name-Beispiel
  • Example#1746 - mysql_db_query-Alternativbeispiel
  • Example#1747 - mysql_drop_db-Alternativbeispiel
  • Example#1748 - mysql_errno-Beispiel
  • Example#1749 - mysql_error-Beispiel
  • Example#1750 - mysql_escape_string-Beispiel
  • Example#1751 - Abfrage mit alias für identische Feldnamen
  • Example#1752 - mysql_fetch_array mit MYSQL_NUM
  • Example#1753 - mysql_fetch_array mit MYSQL_ASSOC
  • Example#1754 - mysql_fetch_array mit MYSQL_BOTH
  • Example#1755 - Ein ausführliches mysql_fetch_assoc-Beispiel
  • Example#1756 - mysql_fetch_field-Beispiel
  • Example#1757 - Ein mysql_fetch_lengths-Beispiel
  • Example#1758 - mysql_fetch_object-Beispiel
  • Example#1759 - mysql_fetch_object-Beispiel
  • Example#1760 - Einen Datensatz mit mysql_fetch_row holen
  • Example#1761 - Ein mysql_field_flags-Beispiel
  • Example#1762 - mysql_field_len-Beispiel
  • Example#1763 - mysql_field_name-Beispiel
  • Example#1764 - Ein mysql_field_table-Beispiel
  • Example#1765 - mysql_field_type-Beispiel
  • Example#1766 - Ein mysql_free_result-Beispiel
  • Example#1767 - mysql_get_client_info-Beispiel
  • Example#1768 - mysql_get_host_info-Beispiel
  • Example#1769 - mysql_get_proto_info-Beispiel
  • Example#1770 - mysql_get_server_info-Beispiel
  • Example#1771 - Relevante MySQL-Anweisungen
  • Example#1772 - mysql_insert_id-Beispiel
  • Example#1773 - mysql_list_dbs-Beispiel
  • Example#1774 - Alternative zum veraltetenmysql_list_fields
  • Example#1775 - mysql_list_processes-Beispiel
  • Example#1776 - mysql_list_tables-Alternativbeispiel
  • Example#1777 - Ein mysql_num_fields-Beispiel
  • Example#1778 - mysql_num_rows-Beispiel
  • Example#1779 - mysql_ping-Beispiel
  • Example#1780 - Ungültige Anfrage
  • Example#1781 - Gültige Anfrage
  • Example#1782 - Einfaches mysql_real_escape_string-Beispiel
  • Example#1783 - mysql_real_escape_string benötigt eine Verbindung
  • Example#1784 - Ein beispielhafter SQL-Injection-Angriff
  • Example#1785 - mysql_result-Beispiel
  • Example#1786 - mysql_select_db-Beispiel
  • Example#1787 - mysql_stat-Beispiel
  • Example#1788 - Alternatives mysql_stat-Beispiel
  • Example#1789 - mysql_tablename-Beispiel
  • Example#1790 - mysql_thread_id-Beispiel
  • Example#1791 - Basic query
  • Example#1792 - Inserting with bind variables
  • Example#1793 - Binding in the WHERE clause of a query
  • Example#1794 - Inserting and fetching a CLOB
  • Example#1795 - Using a PL/SQL stored function
  • Example#1796 - Using a PL/SQL stored procedure
  • Example#1797 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#1798 -
  • Example#1799 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#1800 - oci_bind_array_by_name-Beispiel
  • Example#1801 - Inserting data with oci_bind_by_name
  • Example#1802 - Binding once for multiple executions
  • Example#1803 - Binding with a foreach loop
  • Example#1804 - Binding in a WHERE clause
  • Example#1805 - Binding with a LIKE clause
  • Example#1806 - Binding with REGEXP_LIKE
  • Example#1807 - Binding Multiple Values in an IN Clause
  • Example#1808 - Binding a ROWID returned by a query
  • Example#1809 - Binding a ROWID on INSERT
  • Example#1810 - Binding for a PL/SQL stored function
  • Example#1811 - Binding parameters for a PL/SQL stored procedure
  • Example#1812 - Binding a CLOB column
  • Example#1813 - Binding a PL/SQL BOOLEAN
  • Example#1814 - oci_client_version example
  • Example#1815 - Schließen einer Verbindung
  • Example#1816 - Datenbankverbindungen werden nicht geschlossen, bevor alle Referenzen geschlossen wurden
  • Example#1817 - Schließen einer Verbindung, die mehr als einmal geöffnet wurde
  • Example#1818 - Verbindungen werden geschlossen, wenn die Variablen den Geltungsbereich verlassen
  • Example#1819 - oci_commit example
  • Example#1820 - Basic oci_connect using Easy Connect syntax
  • Example#1821 - Basic oci_connect using a Network Connect name
  • Example#1822 - oci_connect with an explicit character set
  • Example#1823 - Using multiple calls to oci_connect
  • Example#1824 - oci_define_by_name example
  • Example#1825 - oci_define_by_name with case sensitive column names
  • Example#1826 - oci_define_by_name with LOB columns
  • Example#1827 - oci_define_by_name with an explicit type
  • Example#1828 - Zeigt die Oracle-Fehlermeldung nach einem Verbindungsfehler an
  • Example#1829 - Zeigt die Oracle-Fehlermeldung nach einem Parser-Fehler an
  • Example#1830 - Anzeigen der Oracle-Fehlermeldung, der problematischen Anweisung und der Position des Problems nach einem Ausführungsfehler
  • Example#1831 - oci_execute for queries
  • Example#1832 - oci_execute without specifying a mode example
  • Example#1833 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#1834 - oci_execute with different commit modes example
  • Example#1835 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#1836 - oci_fetch_all-Beispiel
  • Example#1837 - oci_fetch_all-Beispiel mit OCI_FETCHSTATEMENT_BY_ROW
  • Example#1838 - oci_fetch_all mit OCI_NUM
  • Example#1839 - oci_fetch_array mit OCI_BOTH
  • Example#1840 - oci_fetch_array mit OCI_NUM
  • Example#1841 - oci_fetch_array mit OCI_ASSOC
  • Example#1842 - oci_fetch_array mit OCI_RETURN_NULLS
  • Example#1843 - oci_fetch_array mit OCI_RETURN_LOBS
  • Example#1844 - oci_fetch_array mit Spaltennamen, die zwischen Groß- und Kleinschreibung unterscheiden
  • Example#1845 - oci_fetch_array mit Spalten, die doppelte Namen haben
  • Example#1846 - oci_fetch_array mit DATE-Spalten
  • Example#1847 - oci_fetch_array mit REF CURSOR
  • Example#1848 - Seitenweise Darstellung mit oci_fetch_array unter Verwendung einer LIMIT-Klausel
  • Example#1849 - oci_fetch_array mit impliziten Ergebnismengen einer Oracle-Datenbank
  • Example#1850 - oci_fetch_assoc-Beispiel
  • Example#1851 - oci_fetch_object-Beispiel
  • Example#1852 - oci_fetch_object mit Spaltennamen, die zwischen Groß- und Kleinschreibung unterscheiden.
  • Example#1853 - oci_fetch_object mit LOBs
  • Example#1854 - oci_fetch_row-Beispiel
  • Example#1855 - oci_fetch mit definierten Variablen
  • Example#1856 - oci_fetch mit oci_result
  • Example#1857 - oci_field_name example
  • Example#1858 - oci_field_name example
  • Example#1859 - oci_field_precision Example
  • Example#1860 - oci_field_scale Example
  • Example#1861 - oci_field_size example
  • Example#1862 - oci_field_type_raw Example
  • Example#1863 - oci_field_type example
  • Example#1864 - Fetching Implicit Result Sets in a loop
  • Example#1865 - Getting child statement handles individually
  • Example#1866 - Explicitly setting the Prefetch Count
  • Example#1867 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#1868 - oci_new_connect example
  • Example#1869 - Binding a REF CURSOR in an Oracle stored procedure call
  • Example#1870 - oci_new_descriptor example
  • Example#1871 - oci_new_descriptor example
  • Example#1872 - oci_num_fields example
  • Example#1873 - oci_num_rows example
  • Example#1874 - oci_parse example for SQL statements
  • Example#1875 - oci_parse example for PL/SQL statements
  • Example#1876 - oci_password_change example changing the password of an already connected user
  • Example#1877 - oci_password_change example of connecting and changing the password in one step
  • Example#1878 - Basic oci_pconnect Example using Easy Connect syntax
  • Example#1879 - oci_fetch with oci_result
  • Example#1880 - oci_rollback example
  • Example#1881 - Rolling back to a SAVEPOINT example
  • Example#1882 - oci_server_version example
  • Example#1883 - Setting the action
  • Example#1884 - Setting the timeout
  • Example#1885 - Setting the client identifier to the application user
  • Example#1886 - Setting the client information
  • Example#1887 - Setting the DBOP
  • Example#1888 - Two scripts can use different versions of myfunc() at the same time
  • Example#1889 - Setting the module name
  • Example#1890 - Changing the LOB prefetch value for a query
  • Example#1891 - Changing the default prefetch value for a query
  • Example#1892 - Changing the default prefetch for a REF CURSOR fetch
  • Example#1893 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#1894 - oci_statement_type example
  • Example#1895 - Beispiel für die Benutzung der PostgreSQL-Erweiterung
  • Example#1896 - benutzerdefinierte PostgreSQL Funktionen Beispiel
  • Example#1897 - pg_affected_rows-Beispiel
  • Example#1898 - pg_cancel_query Beispiel
  • Example#1899 - pg_client_encoding-Beispiel
  • Example#1900 - pg_close-Beispiel
  • Example#1901 - pg_connect benutzen
  • Example#1902 - pg_connection_busy Beispiel
  • Example#1903 - pg_connection_reset Beispiel
  • Example#1904 - pg_connection_status Beispiel
  • Example#1905 - pg_convert-Beispiel
  • Example#1906 - pg_copy_from Beispiel
  • Example#1907 - pg_copy_to-Beispiel
  • Example#1908 - pg_dbname-Beispiel
  • Example#1909 - pg_delete-Beispiel
  • Example#1910 - pg_end_copy Beispiel
  • Example#1911 - pg_escape_bytea-Beispiel
  • Example#1912 - pg_escape_identifier example
  • Example#1913 - pg_escape_literal example
  • Example#1914 - pg_escape_string-Beispiel
  • Example#1915 - pg_execute benutzen:
  • Example#1916 - pg_fetch_all_columns-Beispiel
  • Example#1917 - pg_fetch_all-Beispiel
  • Example#1918 - pg_fetch_array-Beispiel
  • Example#1919 - pg_fetch_assoc-Beispiel
  • Example#1920 - pg_fetch_object-Beispiel
  • Example#1921 - pg_fetch_result-Beispiel
  • Example#1922 - pg_fetch_row-Beispiel
  • Example#1923 - pg_field_is_null-Beispiel
  • Example#1924 - Informationen über Felder abfragen
  • Example#1925 - Die Nummer eines Feldes ermitteln
  • Example#1926 - Informationen über Spalten ermitteln
  • Example#1927 - Informationen über Felder abfragen
  • Example#1928 - Informationen über Felder abfragen
  • Example#1929 - Informationen über Felder holen
  • Example#1930 - Informationen über Felder holen
  • Example#1931 - pg_free_result-Beispiel
  • Example#1932 - PostgreSQL-NOTIFY-Nachricht
  • Example#1933 - PostgreSQL Prozess-ID
  • Example#1934 - pg_get_result-Beispiel
  • Example#1935 - pg_host-Beispiel
  • Example#1936 - pg_insert-Beispiel
  • Example#1937 - pg_last_error-Beispiel
  • Example#1938 - pg_last_notice-Beispiel
  • Example#1939 - pg_last_oid-Beispiel
  • Example#1940 - pg_lo_close Beispiel
  • Example#1941 - pg_lo_create-Beispiel
  • Example#1942 - pg_lo_export Beispiel
  • Example#1943 - pg_lo_import-Beispiel
  • Example#1944 - pg_lo_open-Beispiel
  • Example#1945 - pg_lo_read_all-Beispiel
  • Example#1946 - pg_lo_read-Beispiel
  • Example#1947 - pg_lo_seek-Beispiel
  • Example#1948 - pg_lo_tell-Beispiel
  • Example#1949 - pg_lo_truncate example
  • Example#1950 - pg_lo_unlink Beispiel
  • Example#1951 - pg_lo_write-Beispiel
  • Example#1952 - Metadaten für eine Tabelle ermitteln
  • Example#1953 - pg_num_fields Beispiel
  • Example#1954 - pg_num_rows Beispiel
  • Example#1955 - pg_options-Beispiel
  • Example#1956 - pg_parameter_status-Beispiel
  • Example#1957 - pg_pconnect benutzen:
  • Example#1958 - pg_ping Beispiel
  • Example#1959 - pg_port-Beispiel
  • Example#1960 - pg_prepare-Beispiel
  • Example#1961 - pg_put_line Beispiel
  • Example#1962 - pg_query_params-Beispiel
  • Example#1963 - pg_query-Beispiel
  • Example#1964 - pg_query mit mehreren Anweisungen
  • Example#1965 - pg_result_error_field-Beispiel
  • Example#1966 - pg_result_error-Beispiel
  • Example#1967 - pg_result_seek Beispiel
  • Example#1968 - pg_result_status-Beispiel
  • Example#1969 - pg_select-Beispiel
  • Example#1970 - Die Verwendung von pg_send_execute:
  • Example#1971 - pg_send_prepare Beispiel
  • Example#1972 - pg_send_query_params-Beispiel
  • Example#1973 - pg_send_query-Beispiel
  • Example#1974 - pg_set_client_encoding Beispiel
  • Example#1975 - pg_set_error_context_visibility example
  • Example#1976 - pg_set_error_verbosity Beispiel
  • Example#1977 - pg_trace-Beispiel
  • Example#1978 - pg_transaction_status-Beispiel
  • Example#1979 - pg_tty-Beispiel
  • Example#1980 - pg_unescape_bytea-Beispiel
  • Example#1981 - pg_untrace-Beipiel
  • Example#1982 - pg_update-Beispiel
  • Example#1983 - pg_version-Beispiel
  • Example#1984 - Backup an existing database
  • Example#1985 - SQLite3::changes-Beispiel
  • Example#1986 - SQLite3::close Beispiel
  • Example#1987 - SQLite3::__construct-Beispiel
  • Example#1988 - Beispiel für eine 'max_length'-Aggregierungs-Funktion
  • Example#1989 - SQLite3::createCollation example
  • Example#1990 - SQLite3::createFunction-Beispiel
  • Example#1991 - SQLite3::enableExceptions example
  • Example#1992 - SQLite3::exec-Beispiel
  • Example#1993 - SQLite3::loadExtension-Beispiel
  • Example#1994 - SQLite3::open-Beispiel
  • Example#1995 - SQLite3::openBlob example
  • Example#1996 - Incrementally writing a BLOB
  • Example#1997 - SQLite3::prepare-Beispiel
  • Example#1998 - SQLite3::query-Beispiel
  • Example#1999 - SQLite3::querySingle example
  • Example#2000 - SQLite3::setAuthorizer example
  • Example#2001 - SQLite3::version example
  • Example#2002 - SQLite3Stmt::bindParam Usage
  • Example#2003 - SQLite3Stmt::bindValue example
  • Example#2004 - Inspecting the expanded SQL
  • Example#2005 - sqlsrv_begin_transaction example
  • Example#2006 - sqlsrv_cancel example
  • Example#2007 - sqlsrv_client_info example
  • Example#2008 - sqlsrv_close example
  • Example#2009 - sqlsrv_commit example
  • Example#2010 - Connect using Windows Authentication.
  • Example#2011 - Connect by specifying a user name and password.
  • Example#2012 - Connect on a specified port.
  • Example#2013 - functionname example
  • Example#2014 - sqlsrv_execute example
  • Example#2015 - Retrieving an associative array.
  • Example#2016 - Retrieving a numeric array.
  • Example#2017 - sqlsrv_fetch_object example
  • Example#2018 - sqlsrv_fetch example
  • Example#2019 - sqlsrv_field_metadata example
  • Example#2020 - sqlsrv_free_stmt example
  • Example#2021 - sqlsrv_get_field example
  • Example#2022 - sqlsrv_has_rows example
  • Example#2023 - sqlsrv_next_result example
  • Example#2024 - sqlsrv_num_fields example
  • Example#2025 - sqlsrv_num_rows example
  • Example#2026 - sqlsrv_prepare example
  • Example#2027 - sqlsrv_query example
  • Example#2028 - sqlsrv_rollback example
  • Example#2029 - sqlsrv_rows_affected example
  • Example#2030 - sqlsrv_send_stream_data example
  • Example#2031 - sqlsrv_server_info example
  • Example#2032 - cal_days_in_month Beispiel
  • Example#2033 - cal_from_jd-Beispiel
  • Example#2034 - cal_info Beispiel
  • Example#2035 - easter_date-Beispiel
  • Example#2036 - Verwendung von easter_date mit DateTime
  • Example#2037 - easter_days Beispiel
  • Example#2038 - Caledar Funktionen
  • Example#2039 - Überlaufverhalten
  • Example#2040 - jdtojewish-Beispiel
  • Example#2041 - DateTimeImmutable::add/sub addiert Intervalle, die die verstrichene Zeit umfassen
  • Example#2042 - DateTimeImmutable::modify und strtotime erhöhen oder verringern die Werte einzelner Komponenten
  • Example#2043 - Durch die Addition oder Subtraktion von Zeiten kann das Datum über- oder unterschritten werden
  • Example#2044 - Erstellen eines veränderbaren DateTime-Objekts
  • Example#2045 - Erstellen eines veränderbaren DateTime-Objekts
  • Example#2046 - DateTime::modify-Beispiel
  • Example#2047 - Vorsicht beim Addieren oder Subtrahieren von Monaten
  • Example#2048 - Alle Formate von Datum und Zeit werden unterstützt
  • Example#2049 - DateTime::setTimeZone-Beispiel
  • Example#2050 - DateTimeImmutable::add-Beispiel
  • Example#2051 - Weitere DateTimeImmutable::add-Beispiele
  • Example#2052 - Vorsicht beim Addieren von Monaten
  • Example#2053 - DateTimeImmutable::__construct-Beispiel
  • Example#2054 - Die Besonderheiten von DateTimeImmutable::__construct
  • Example#2055 - Ändern der zugehörigen Zeitzone
  • Example#2056 - Verwenden einer Zeichenkette mit relativen Datums- und Zeitangaben
  • Example#2057 - DateTimeImmutable::createFromFormat-Beispiel
  • Example#2058 - Verwendung von DateTimeImmutable::createFromFormat mit vordefinierten Formatkonstanten
  • Example#2059 - Besonderheiten von DateTimeImmutable::createFromFormat
  • Example#2060 - Formatzeichenkette mit literalen Zeichen
  • Example#2061 - Verhalten bei einem Überlauf
  • Example#2062 - Verhalten bei überlaufenden Tagesnamen
  • Example#2063 - Erkennen von übergelaufenen Daten
  • Example#2064 - Gieriges Verhalten beim Auswerten
  • Example#2065 - Erstellen eines unveränderbaren DateTime-Objekts
  • Example#2066 - Erstellen eines nicht veränderbaren DateTime-Objekts
  • Example#2067 - DateTimeImmutable::getLastErrors-Beispiel
  • Example#2068 - DateTimeImmutable::modify-Beispiel
  • Example#2069 - Vorsicht beim Addieren oder Subtrahieren von Monaten
  • Example#2070 - DateTimeImmutable::setDate-Beispiel
  • Example#2071 - Werte, die einen Bereich überschreiten, werden zu ihren übergeordneten Werten hinzugefügt
  • Example#2072 - DateTimeImmutable::setISODate-Beispiel
  • Example#2073 - Werte, die einen Bereich überschreiten, werden zu ihren übergeordneten Werten hinzugefügt
  • Example#2074 - Ermitteln des Monats, in dem eine Woche liegt
  • Example#2075 - DateTimeImmutable::setTime-Beispiel
  • Example#2076 - Werte, die einen Bereich überschreiten, werden zu ihren übergeordneten Werten hinzugefügt
  • Example#2077 - DateTimeImmutable::setTimestamp-Beispiel
  • Example#2078 - DateTimeImmutable::setTimeZone-Beispiel
  • Example#2079 - DateTimeImmutable::sub-Beispiel
  • Example#2080 - Weitere DateTimeImmutable::sub-Beispiele
  • Example#2081 - Vorsicht beim Subtrahieren von Monaten
  • Example#2082 - DateTimeImmutable::diff-Beispiel
  • Example#2083 - DateTimeInterface::diff während der Zeitumstellung
  • Example#2084 - Zeitspanne von DateTimeInterface::diff
  • Example#2085 - Vergleich von DateTime-Objekten
  • Example#2086 - DateTimeInterface::format-Beispiel
  • Example#2087 - Weitere Beispiele
  • Example#2088 - Zeichen beim Formatieren maskieren
  • Example#2089 - DateTime::getOffset-Beispiel
  • Example#2090 - DateTime::getTimestamp-Beispiel
  • Example#2091 - Auslesen des Zeitstempels mit einer Auflösung im Milli- und Mikrosekundenbereich
  • Example#2092 - DateTime::getTimezone-Beispiel
  • Example#2093 - Erstellen und Anhängen von DateTimeZone an ein DateTimeImmutable
  • Example#2094 - Fehler beim Initialisieren von DateTimeZone abfangen
  • Example#2095 - DateTimeZone::getLocation-Beispiel
  • Example#2096 - DateTimeZone::getOffset-Beispiele
  • Example#2097 - timezone_transitions_get-Beispiel
  • Example#2098 - timezone_transitions_get-Beispiel mit gesetztem timestampBegin
  • Example#2099 - timezone_abbreviations_list-Beispiel
  • Example#2100 - DateTimeZone::listIdentifiers-Beispiel
  • Example#2101 - Auflisten der Bezeichner für eine bestimmte Region
  • Example#2102 - Auflisten der Bezeichner für mehrere Regionen
  • Example#2103 - Auflisten der Bezeichner für ein einzelnes Land
  • Example#2104 - Erstellen und Verwenden von DateInterval-Objekten
  • Example#2105 - DateInterval-Beispiel
  • Example#2106 - Parsen gültiger Datums-Intervalle
  • Example#2107 - Parsen von Kombinationen und negativen Intervallen
  • Example#2108 - Parsen spezieller relativer Datums-Intervalle
  • Example#2109 - DateInterval-Beispiel
  • Example#2110 - DateInterval und Überträge
  • Example#2111 - DateInterval und DateTime::diff mit den Modifikatoren %a und %d
  • Example#2112 - DatePeriod-Beispiel
  • Example#2113 - DatePeriod-Beispiel mit DatePeriod::EXCLUDE_START_DATE
  • Example#2114 - Ein DatePeriod-Beispiel, das alle letzten Donnerstage eines Jahres anzeigt
  • Example#2115 - DatePeriod::createFromISO8601String-Beispiel
  • Example#2116 - DatePeriod::getDateInterval-Beispiel
  • Example#2117 - DatePeriod::getEndDate-Beispiel
  • Example#2118 - DatePeriod::getEndDate ohne Enddatum
  • Example#2119 - Unterschiedliche Werte bei DatePeriod::getRecurrences
  • Example#2120 - DatePeriod::getStartDate-Beispiel
  • Example#2121 - checkdate-Beispiel
  • Example#2122 - Ermitteln der Standardzeitzone
  • Example#2123 - Ermitteln der Abkürzung einer Zeitzone
  • Example#2124 - Ermittlung der Standardzeitzone
  • Example#2125 - date_parse_from_format-Beispiel
  • Example#2126 - date_parse_from_format-Beispiel mit Warnungen
  • Example#2127 - date_parse_from_format-Beispiel mit Fehlern
  • Example#2128 - Ein date_parse-Beispiel mit einer vollständigen datetime-Zeichenkette
  • Example#2129 - date_parse mit Zeitzonenkürzel
  • Example#2130 - date_parse mit Zeitzonenkennung
  • Example#2131 - date_parse mit einer minimalen Zeichenkette
  • Example#2132 - date_parse mit relativen Formaten
  • Example#2133 - date_parse mit Nebeneffekten
  • Example#2134 - Ein date_sun_info-Beispiel
  • Example#2135 - Polarnacht mit etwas Nachbearbeitung
  • Example#2136 - Mitternachtssonne (Tromsø, Norwegen)
  • Example#2137 - Berechnung der Länge des Tages (Kiew)
  • Example#2138 - date_sunrise-Beispiel
  • Example#2139 - Kein Sonnenaufgang
  • Example#2140 - date_sunset-Beispiel
  • Example#2141 - Kein Sonnenuntergang
  • Example#2142 - date-Beispiele
  • Example#2143 - Maskieren von Zeichen in date
  • Example#2144 - date und mktime-Beispiele
  • Example#2145 - date-Formatierungen
  • Example#2146 - getdate-Beispiel
  • Example#2147 - gettimeofday-Beispiel
  • Example#2148 - gmdate-Beispiel
  • Example#2149 - Grundlegendes gmmktime-Beispiel
  • Example#2150 - gmstrftime-Beispiel
  • Example#2151 - idate-Beispiel
  • Example#2152 - localtime-Beispiel
  • Example#2153 - Zeitmessung einer Skriptausführung
  • Example#2154 - microtime und REQUEST_TIME_FLOAT
  • Example#2155 - Einfaches mktime-Beispiel
  • Example#2156 - mktime-Beispiel
  • Example#2157 - Letzter Tag eines Monats
  • Example#2158 - strftime-Gebietsschema-Beispiele
  • Example#2159 - ISO 8601:1988 Wochennummer-Beispiel
  • Example#2160 - Plattformübergreifendes Beispiel unter Verwendung des Platzhalters %e
  • Example#2161 - Zeige alle bekannten und unbekannten Formate an.
  • Example#2162 - strptime-Beispiel
  • Example#2163 - Ein strtotime-Beispiel
  • Example#2164 - Test auf Fehler
  • Example#2165 - time-Beispiel
  • Example#2166 - Ein timezone_name_from_abbr-Beispiel
  • Example#2167 - Ermitteln der timezonedb-Version
  • Example#2168 - Measure several code blocks execution and get the total
  • Example#2169 - Schließen eines geöffneten Dateideskriptors
  • Example#2170 - Setzen und Löschen einer Sperre
  • Example#2171 - Öffnen eines Dateideskriptors
  • Example#2172 - Positionieren in einer Datei
  • Example#2173 - Einstellen der Baudrate an einer seriellen Schnittstelle
  • Example#2174 - chdir Beispiel
  • Example#2175 - chroot-Beispiel
  • Example#2176 - closedir-Beispiel
  • Example#2177 - dir-Beispiel
  • Example#2178 - getcwd-Beispiel
  • Example#2179 - opendir-Beispiel
  • Example#2180 - Alle Einträge eines Verzeichnisses auflisten
  • Example#2181 - Listet alle Einträge des aktuellen Verzeichnisses auf und blendet dabei die Verzeichnisse . und .. aus.
  • Example#2182 - Ein einfaches scandir-Beispiel
  • Example#2183 - A finfo_buffer example
  • Example#2184 - Ein finfo_file-Beispiel
  • Example#2185 - Objektorientierter Stil
  • Example#2186 - Prozeduraler Stil
  • Example#2187 - mime_content_type Example
  • Example#2188 - basename-Beispiel
  • Example#2189 - Gruppe einer Datei ändern
  • Example#2190 - Einfache chown-Benutzung
  • Example#2191 - clearstatcache-Beispiel
  • Example#2192 - copy-Beispiel
  • Example#2193 - dirname-Beispiel
  • Example#2194 - disk_free_space-Beispiel
  • Example#2195 - disk_total_space-Beispiel
  • Example#2196 - Ein einfaches fclose Beispiel
  • Example#2197 - fdatasync example
  • Example#2198 - Handhabung von Zeitüberschreitungen mit feof
  • Example#2199 - feof-Beispiel mit einem ungültigen Dateizeiger
  • Example#2200 - File write example using fflush
  • Example#2201 - Ein fgetc-Beispiel
  • Example#2202 - Lesen und Ausgeben des gesamten Inhalts einer CSV-Datei
  • Example#2203 - Eine Datei Zeile für Zeile lesen
  • Example#2204 - Reading a PHP file line-by-line
  • Example#2205 - Prüfen, ob eine Datei existiert
  • Example#2206 - Holen und Ausgeben des Quelltextes der Startseite einer Webseite
  • Example#2207 - Suche im include_path
  • Example#2208 - Lesen einen Abschnitts einer Datei
  • Example#2209 - Nutzung von Stream-Contexten
  • Example#2210 - Einfaches Verwendungsbeispiel
  • Example#2211 - Verwendung der Flags
  • Example#2212 - file-Beispiel
  • Example#2213 - fileatime-Beispiel
  • Example#2214 - filectime-Beispiel
  • Example#2215 - Finding the group of a file
  • Example#2216 - Vergleich des Inodes einer Datei mit dem der aktuellen Datei
  • Example#2217 - filemtime-Beispiel
  • Example#2218 - Den Eigentümer einer Datei finden
  • Example#2219 - Zeige die Zugriffsrechte als Oktalwert an
  • Example#2220 - Zeige die kompletten Zugriffsrechte an
  • Example#2221 - filesize-Beispiel
  • Example#2222 - filetype-Beispiel
  • Example#2223 - flock-Beispiel
  • Example#2224 - flock mit der Option LOCK_NB
  • Example#2225 - Checking a color name against a shell wildcard pattern
  • Example#2226 - fopen-Beispiele
  • Example#2227 - Nutzung von fpassthru mit binären Dateien
  • Example#2228 - fputcsv example
  • Example#2229 - Ein einfaches fread-Beispiel
  • Example#2230 - Ein fread-Beispiel mit einer Binärdatei
  • Example#2231 - fread-Beispiele für entfernte Dateien
  • Example#2232 - fscanf-Beispiel
  • Example#2233 - Inhalt der Datei users.txt
  • Example#2234 - fseek Beispiel
  • Example#2235 - fstat-Beispiel
  • Example#2236 - fsync example
  • Example#2237 - ftell Beispiel
  • Example#2238 - Dateikürzungsbeispiel
  • Example#2239 - Ein einfaches Beispiel für fwrite
  • Example#2240 - Einfacher Ersatz von opendir etc. durch glob
  • Example#2241 - is_dir-Beispiel
  • Example#2242 - is_executable-Beispiel
  • Example#2243 - is_file-Beispiel
  • Example#2244 - Erstelle und bestätige, dass eine Datei ein symbolischer Link ist
  • Example#2245 - is_readable-Beispiel
  • Example#2246 - is_uploaded_file-Beispiel
  • Example#2247 - is_writable-Beispiel
  • Example#2248 - Changing the group of a symbolic link
  • Example#2249 - Changing the owner of a symbolic link
  • Example#2250 - Erstellen eines harten Links
  • Example#2251 - linkinfo-Beispiel
  • Example#2252 - Vergleich von stat und lstat
  • Example#2253 - mkdir-Beispiel
  • Example#2254 - mkdir mit dem Parameter recursive benutzen
  • Example#2255 - Hochladen mehrerer Dateien
  • Example#2256 - Inhalt der sample.ini
  • Example#2257 - parse_ini_file-Beispiel
  • Example#2258 - parse_ini_file parst eine php.ini
  • Example#2259 - Wert-Interpolation
  • Example#2260 - Zeichen maskieren
  • Example#2261 - pathinfo-Beispiel
  • Example#2262 - pathinfo-Beispiel für den Unterschied zwischen einer leeren und keiner Erweiterung
  • Example#2263 - pathinfo-Beispiel für eine Punktdatei
  • Example#2264 - pathinfo-Beispiel mit Array-Dereferenzierung
  • Example#2265 - pclose Beispiel
  • Example#2266 - popen-Beispiel
  • Example#2267 - popen-Beispiel
  • Example#2268 - Einen Download unter Verwendung von readfile erzwingen
  • Example#2269 - readlink example
  • Example#2270 - realpath_cache_get example
  • Example#2271 - realpath_cache_size example
  • Example#2272 - realpath
  • Example#2273 - realpath auf Windows
  • Example#2274 - Beispiel mit rename
  • Example#2275 - Beispiel zum Überschreiben mit rewind
  • Example#2276 - rmdir Beispiel
  • Example#2277 - stat-Beispiel
  • Example#2278 - Nutzung von stat-Informationen zusammen mit touch
  • Example#2279 - Einen symbolischen Link erzeugen
  • Example#2280 - tempnam-Beispiel
  • Example#2281 - tmpfile-Beispiel
  • Example#2282 - touch-Beispiel
  • Example#2283 - Nutzung von touch mit dem Parameter mtime
  • Example#2284 - umask-Beispiel
  • Example#2285 - Einfache Nutzung von unlink
  • Example#2286 - Example usage of inotify
  • Example#2287 - Checks if system administrator has signed the file
  • Example#2288 - Prints names of all extended attributes of file
  • Example#2289 - Removes all extended attributes of a file
  • Example#2290 - Sets extended attributes on .wav file
  • Example#2291 - xattr_supported example
  • Example#2292 - xdiff_file_bdiff_size example
  • Example#2293 - xdiff_file_bdiff example
  • Example#2294 - xdiff_file_bpatch example
  • Example#2295 - xdiff_file_diff_binary example
  • Example#2296 - xdiff_file_diff example
  • Example#2297 - xdiff_file_merge3 example
  • Example#2298 - xdiff_file_patch_binary example
  • Example#2299 - xdiff_file_patch example
  • Example#2300 - Patch reversing example
  • Example#2301 - xdiff_file_rabdiff example
  • Example#2302 - xdiff_string_bdiff_size example
  • Example#2303 - xdiff_string_diff example
  • Example#2304 - xdiff_string_patch example
  • Example#2305 - Enchant Usage Example
  • Example#2306 - List the backends provided by the given broker
  • Example#2307 - A enchant_broker_dict_exists example
  • Example#2308 - List all available dictionaries for one broker
  • Example#2309 - A enchant_broker_request_dict example
  • Example#2310 - Adding a word to a PWL
  • Example#2311 - A enchant_dict_describe example
  • Example#2312 - A enchant_dict_quick_check example
  • Example#2313 - A enchant_dict_suggest example
  • Example#2314 - Beispiel.
  • Example#2315 - Using Gender\Gender::country
  • Example#2316 - bindtextdomain-Beispiel
  • Example#2317 - gettext-Suche
  • Example#2318 - ngettext-Beispiel
  • Example#2319 - iconv_get_encoding-Beispiel
  • Example#2320 - iconv_mime_decode_headers example
  • Example#2321 - iconv_mime_decode example
  • Example#2322 - iconv_mime_encode example
  • Example#2323 - iconv_set_encoding-Beispiel:
  • Example#2324 - iconv-Beispiel:
  • Example#2325 - ob_iconv_handler-Beispiel
  • Example#2326 - Example of using the procedural API
  • Example#2327 - Example of using the object-oriented API
  • Example#2328 - FRENCH_COLLATION rules
  • Example#2329 - ALTERNATE_HANDLING rules
  • Example#2330 - CASE_FIRST rules
  • Example#2331 - CASE_LEVEL rules
  • Example#2332 - collator_asort example
  • Example#2333 - collator_compare example
  • Example#2334 - Comparing strings without diacritics or case-sensitivity
  • Example#2335 - Collator::__construct example
  • Example#2336 - collator_create example
  • Example#2337 - collator_get_attribute example
  • Example#2338 - collator_get_error_code example
  • Example#2339 - collator_get_error_message example
  • Example#2340 - collator_get_locale example
  • Example#2341 - collator_get_sort_keyexample
  • Example#2342 - collator_get_strength example
  • Example#2343 - collator_set_attribute example
  • Example#2344 - collator_set_strength example
  • Example#2345 - collator_sort_with_sort_keys example
  • Example#2346 - collator_sort example
  • Example#2347 - numfmt_create example
  • Example#2348 - NumberFormatter::create example
  • Example#2349 - numfmt_format_currency example
  • Example#2350 - OO example
  • Example#2351 - numfmt_format example
  • Example#2352 - OO example
  • Example#2353 - numfmt_get_attribute example
  • Example#2354 - OO example
  • Example#2355 - numfmt_get_error_code example
  • Example#2356 - OO example
  • Example#2357 - numfmt_get_error_message example
  • Example#2358 - OO example
  • Example#2359 - numfmt_get_locale example
  • Example#2360 - numfmt_get_pattern example
  • Example#2361 - OO example
  • Example#2362 - numfmt_get_symbol example
  • Example#2363 - OO example
  • Example#2364 - numfmt_get_text_attribute example
  • Example#2365 - OO example
  • Example#2366 - numfmt_parse_currency example
  • Example#2367 - OO example
  • Example#2368 - numfmt_parse example
  • Example#2369 - OO example
  • Example#2370 - numfmt_set_attribute example
  • Example#2371 - OO example
  • Example#2372 - numfmt_set_pattern example
  • Example#2373 - OO example
  • Example#2374 - numfmt_set_symbol example
  • Example#2375 - OO example
  • Example#2376 - numfmt_set_text_attribute example
  • Example#2377 - OO example
  • Example#2378 - locale_accept_from_http example
  • Example#2379 - OO example
  • Example#2380 - locale_compose example
  • Example#2381 - OO example
  • Example#2382 - Subtag limits
  • Example#2383 - locale_filter_matches example
  • Example#2384 - OO example
  • Example#2385 - locale_get_all_variants example
  • Example#2386 - OO example
  • Example#2387 - locale_get_default example
  • Example#2388 - OO example
  • Example#2389 - locale_get_display_language example
  • Example#2390 - OO example
  • Example#2391 - locale_get_display_name example
  • Example#2392 - OO example
  • Example#2393 - locale_get_display_region example
  • Example#2394 - OO example
  • Example#2395 - locale_get_display_script example
  • Example#2396 - OO example
  • Example#2397 - locale_get_display_variant example
  • Example#2398 - OO example
  • Example#2399 - locale_get_keywords example
  • Example#2400 - OO example
  • Example#2401 - locale_get_primary_language example
  • Example#2402 - OO example
  • Example#2403 - locale_get_region example
  • Example#2404 - OO example
  • Example#2405 - locale_get_script example
  • Example#2406 - OO example
  • Example#2407 - locale_lookup example
  • Example#2408 - OO example
  • Example#2409 - locale_parse example
  • Example#2410 - OO example
  • Example#2411 - locale_set_default example
  • Example#2412 - OO example
  • Example#2413 - Normalizer::getRawDecomposition example
  • Example#2414 - normalizer_is_normalized example
  • Example#2415 - OO example
  • Example#2416 - normalizer_normalize example
  • Example#2417 - OO example
  • Example#2418 - msgfmt_create example
  • Example#2419 - OO example
  • Example#2420 - msgfmt_format_message example
  • Example#2421 - OO example
  • Example#2422 - Instructing ICU to format currency with common and with narrow currency symbol
  • Example#2423 - msgfmt_format example
  • Example#2424 - OO example
  • Example#2425 - msgfmt_get_error_message example
  • Example#2426 - OO example
  • Example#2427 - msgfmt_get_locale example
  • Example#2428 - OO example
  • Example#2429 - msgfmt_get_pattern example
  • Example#2430 - OO example
  • Example#2431 - msgfmt_parse_message example
  • Example#2432 - OO example
  • Example#2433 - msgfmt_parse example
  • Example#2434 - OO example
  • Example#2435 - msgfmt_set_pattern example
  • Example#2436 - OO example
  • Example#2437 - IntlCalendar::add
  • Example#2438 - IntlCalendar::after
  • Example#2439 - IntlCalendar::clear examples
  • Example#2440 - IntlCalendar::createInstance
  • Example#2441 - IntlCalendar::equals
  • Example#2442 - IntlCalendar::fieldDifference
  • Example#2443 - IntlCalendar::fromDateTime
  • Example#2444 - IntlCalendar::get
  • Example#2445 - IntlCalendar::getActualMaximum
  • Example#2446 - IntlCalendar::getAvailableLocales
  • Example#2447 - IntlCalendar::getDayOfWeekType
  • Example#2448 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2449 - IntlCalendar::getErrorMessage
  • Example#2450 - IntlCalendar::getFirstDayOfWeek
  • Example#2451 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2452 - Maxima examples
  • Example#2453 - IntlCalendar::getLocale
  • Example#2454 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2455 - IntlCalendar::getNow
  • Example#2456 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2457 - IntlCalendar::getSkippedWallTimeOption
  • Example#2458 - IntlCalendar::getTime
  • Example#2459 - IntlCalendar::getTimeZone
  • Example#2460 - IntlCalendar::getType
  • Example#2461 - IntlCalendar::inDaylightTime
  • Example#2462 - IntlCalendar::isEquivalentTo
  • Example#2463 - IntlCalendar::isLenient
  • Example#2464 - IntlCalendar::isWeekend
  • Example#2465 - IntlCalendar::roll
  • Example#2466 - IntlCalendar::set
  • Example#2467 - IntlCalendar::setDate example
  • Example#2468 - IntlCalendar::setDateTime example
  • Example#2469 - IntlCalendar::setFirstDayOfWeek
  • Example#2470 - IntlCalendar::setTime
  • Example#2471 - IntlCalendar::setTimeZone
  • Example#2472 - IntlCalendar::toDateTime
  • Example#2473 - IntlGregorianCalendar::createFromDate example
  • Example#2474 - IntlGregorianCalendar::createFromDateTime example
  • Example#2475 - datefmt_create example
  • Example#2476 - OO example
  • Example#2477 - Example of invalid locale handling
  • Example#2478 - datefmt_format example
  • Example#2479 - OO example
  • Example#2480 - With IntlCalendar object
  • Example#2481 - IntlDateFormatter::formatObject examples
  • Example#2482 - datefmt_get_calendar example
  • Example#2483 - OO example
  • Example#2484 - Example of invalid locale handling
  • Example#2485 - datefmt_get_datetype example
  • Example#2486 - OO example
  • Example#2487 - datefmt_get_error_code example
  • Example#2488 - OO example
  • Example#2489 - datefmt_get_error_message example
  • Example#2490 - OO example
  • Example#2491 - datefmt_get_locale example
  • Example#2492 - OO example
  • Example#2493 - datefmt_get_pattern example
  • Example#2494 - OO example
  • Example#2495 - datefmt_get_timetype example
  • Example#2496 - OO example
  • Example#2497 - datefmt_get_timezone_id example
  • Example#2498 - OO example
  • Example#2499 - IntlDateFormatter::getCalendarObject example
  • Example#2500 - IntlDateFormatter::getTimeZone examples
  • Example#2501 - datefmt_is_lenient example
  • Example#2502 - OO example
  • Example#2503 - datefmt_localtime example
  • Example#2504 - OO example
  • Example#2505 - OO example
  • Example#2506 - datefmt_parse example
  • Example#2507 - datefmt_set_calendar example
  • Example#2508 - OO example
  • Example#2509 - Example with IntlCalendar argument
  • Example#2510 - datefmt_set_lenient example
  • Example#2511 - OO example
  • Example#2512 - datefmt_set_pattern example
  • Example#2513 - OO example
  • Example#2514 - IntlDateFormatter::setTimeZone examples
  • Example#2515 - resourcebundle_count example
  • Example#2516 - OO example
  • Example#2517 - resourcebundle_create example
  • Example#2518 - ResourceBundle::create example
  • Example#2519 - resourcebundle_get_error_code example
  • Example#2520 - OO example
  • Example#2521 - resourcebundle_get_error_message example
  • Example#2522 - OO example
  • Example#2523 - resourcebundle_get example
  • Example#2524 - OO example
  • Example#2525 - resourcebundle_locales example
  • Example#2526 - OO example
  • Example#2527 - Spoofchecker::areConfusable example
  • Example#2528 - Spoofchecker::isSuspicious example
  • Example#2529 - Retrieving the registered transliterator IDs
  • Example#2530 - Converting escaped UTF-16 code units
  • Example#2531 - IntlDatePatternGenerator::getBestPattern example
  • Example#2532 - Converting from UTF-8 to UTF-16 and back
  • Example#2533 - Invalid characters in input
  • Example#2534 - Characters which cannot be encoded
  • Example#2535 - grapheme_extract example
  • Example#2536 - grapheme_stripos example
  • Example#2537 - grapheme_stristr example
  • Example#2538 - grapheme_strlen example
  • Example#2539 - grapheme_strpos example
  • Example#2540 - grapheme_strripos example
  • Example#2541 - grapheme_strrpos example
  • Example#2542 - grapheme_strstr example
  • Example#2543 - grapheme_substr example
  • Example#2544 - idn_to_ascii example
  • Example#2545 - idn_to_utf8 example
  • Example#2546 - Testen unterschiedlicher Codepoints
  • Example#2547 - Testen unterschiedlicher Codepoints
  • Example#2548 - Testen unterschiedlicher Codepoints
  • Example#2549 - Testen unterschiedlicher Codepoints
  • Example#2550 - Testen unterschiedlicher Codepoints
  • Example#2551 - Testen unterschiedlicher Codepoints
  • Example#2552 - Testen unterschiedlicher Codepoints
  • Example#2553 - Testen unterschiedlicher Codepoints
  • Example#2554 - Testen unterschiedlicher Codepoints
  • Example#2555 - Enumerating over a sample range of code points
  • Example#2556 - Enumerating over a sample range of code points
  • Example#2557 - Testen unterschiedlicher Codepoints
  • Example#2558 - Testen unterschiedlicher Codepoints
  • Example#2559 - Testen unterschiedlicher Codepoints
  • Example#2560 - Testen unterschiedlicher Codepoints
  • Example#2561 - Testen unterschiedlicher Codepoints
  • Example#2562 - Testen unterschiedlicher Eigenschaften
  • Example#2563 - Testen unterschiedlicher Eigenschaften
  • Example#2564 - Testen unterschiedlicher Eigenschaften
  • Example#2565 - Testen unterschiedlicher Codepoints
  • Example#2566 - Testen unterschiedlicher Eigenschaften
  • Example#2567 - Testen unterschiedlicher Eigenschaften
  • Example#2568 - Testen unterschiedlicher Eigenschaften
  • Example#2569 - Testen unterschiedlicher Eigenschaften
  • Example#2570 - Testen unterschiedlicher Eigenschaften
  • Example#2571 - Testen unterschiedlicher Eigenschaften
  • Example#2572 - Testen unterschiedlicher Codepoints
  • Example#2573 - Testen unterschiedlicher Codepoints
  • Example#2574 - Testen unterschiedlicher Codepoints
  • Example#2575 - Testen unterschiedlicher Codepoints
  • Example#2576 - Testen unterschiedlicher Codepoints
  • Example#2577 - Testen unterschiedlicher Codepoints
  • Example#2578 - Testen unterschiedlicher Codepoints
  • Example#2579 - Testen unterschiedlicher Codepoints
  • Example#2580 - Testen unterschiedlicher Codepoints
  • Example#2581 - Testen unterschiedlicher Codepoints
  • Example#2582 - Testen unterschiedlicher Codepoints
  • Example#2583 - Testen unterschiedlicher Codepoints
  • Example#2584 - Testen unterschiedlicher Codepoints
  • Example#2585 - Testen unterschiedlicher Codepoints
  • Example#2586 - Testen unterschiedlicher Codepoints
  • Example#2587 - Testen unterschiedlicher Codepoints
  • Example#2588 - Testen unterschiedlicher Codepoints
  • Example#2589 - Testen unterschiedlicher Codepoints
  • Example#2590 - Testen unterschiedlicher Codepoints
  • Example#2591 - Testen unterschiedlicher Codepoints
  • Example#2592 - Testen unterschiedlicher Codepoints
  • Example#2593 - Testen unterschiedlicher Codepoints
  • Example#2594 - Testen unterschiedlicher Codepoints
  • Example#2595 - Testen unterschiedlicher Codepoints
  • Example#2596 - Testen unterschiedlicher Codepoints
  • Example#2597 - Testen unterschiedlicher Codepoints
  • Example#2598 - Testen unterschiedlicher Codepoints
  • Example#2599 - Testen unterschiedlicher Codepoints
  • Example#2600 - Testen unterschiedlicher Codepoints
  • Example#2601 - Testen unterschiedlicher Codepoints
  • Example#2602 - Testen unterschiedlicher Codepoints
  • Example#2603 - Testen unterschiedlicher Codepoints
  • Example#2604 - intl_error_name example
  • Example#2605 - intl_get_error_code example
  • Example#2606 - intl_get_error_message example
  • Example#2607 - intl_is_failure example
  • Example#2608 - php.ini setting examples
  • Example#2609 - php.ini setting for EUC-JP users
  • Example#2610 - php.ini setting for SJIS users
  • Example#2611 - Disable HTTP input conversion in php.ini
  • Example#2612 - php.ini setting example
  • Example#2613 - Script example
  • Example#2614 - Testen unterschiedlicher Codepoints
  • Example#2615 - mb_convert_case example
  • Example#2616 - mb_convert_case example with non-Latin UTF-8 text
  • Example#2617 - mb_convert_encoding example
  • Example#2618 - mb_convert_kana example
  • Example#2619 - mb_convert_variables example
  • Example#2620 - map example
  • Example#2621 - map example escapes JavaScript string
  • Example#2622 - mb_detect_encoding example
  • Example#2623 - Effect of strict parameter
  • Example#2624 - Effect of order when multiple encodings match
  • Example#2625 - mb_detect_order examples
  • Example#2626 - Example showing useless detect orders
  • Example#2627 - mb_encode_mimeheader example
  • Example#2628 - map example
  • Example#2629 - mb_encode_numericentity example
  • Example#2630 - mb_encoding_aliases example
  • Example#2631 - mb_ereg_replace_callback example
  • Example#2632 - mb_ereg_replace_callback using anonymous function
  • Example#2633 - mb_internal_encoding example
  • Example#2634 - mb_list_encodings example
  • Example#2635 - A basic mb_ord example
  • Example#2636 - mb_output_handler example
  • Example#2637 - mb_preferred_mime_name example
  • Example#2638 - mb_str_pad example
  • Example#2639 - mb_strimwidth example
  • Example#2640 - mb_strtolower example
  • Example#2641 - mb_strtolower example with non-Latin UTF-8 text
  • Example#2642 - mb_strtoupper example
  • Example#2643 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#2644 - mb_strwidth example
  • Example#2645 - mb_substitute_character example
  • Example#2646 - mb_substr_count example
  • Example#2647 - pspell_add_to_personal-Beispiel
  • Example#2648 - pspell_check-Beispiel
  • Example#2649 - pspell_add_to_personal-Beispiel
  • Example#2650 - pspell_config_create-Beispiel
  • Example#2651 - pspell_config_ignore-Beispiel
  • Example#2652 - pspell_config_mode-Beispiel
  • Example#2653 - pspell_config_personal-Beispiel
  • Example#2654 - pspell_config_repl-Beispiel
  • Example#2655 - pspell_config_runtogether-Beispiel
  • Example#2656 - pspell_new_config-Beispiel
  • Example#2657 - pspell_new_personal-Beispiel
  • Example#2658 - pspell_new-Beispiel
  • Example#2659 - pspell_add_to_personal-Beispiel
  • Example#2660 - pspell_store_replacement-Beispiel
  • Example#2661 - pspell_suggest-Beispiel
  • Example#2662 - Einfaches recode_file-Beispiel
  • Example#2663 - Einfaches recode_string-Beispiel:
  • Example#2664 - exif_imagetype-Beispiel
  • Example#2665 - exif_read_data-Beispiel
  • Example#2666 - exif_read_data mit Streams; verfügbar von PHP 7.2.0 an
  • Example#2667 - exif_tagname Beispiel
  • Example#2668 - exif_thumbnail-Beispiel
  • Example#2669 - PNG erzeugen mit PHP
  • Example#2670 - Wasserzeichen mit Hilfe von Alpha-Kanälen zufügen
  • Example#2671 - Erstellen eines transparenten Wasserzeichens mit imagecopymerge
  • Example#2672 - Verwendung von gd_info
  • Example#2673 - getimagesize und MIME-Typ
  • Example#2674 - getimagesize-Beispiel
  • Example#2675 - getimagesize (URL)
  • Example#2676 - getimagesize mit Rückgabe von IPTC
  • Example#2677 - getimagesizefromstring-Beispiel
  • Example#2678 - image_type_to_extension example
  • Example#2679 - image_type_to_mime_type example
  • Example#2680 - image2wbmp example
  • Example#2681 - imageaffinematrixconcat example
  • Example#2682 - imageaffinematrixget example
  • Example#2683 - imagealphablending usage example
  • Example#2684 - A comparison of two lines, one with anti-aliasing switched on
  • Example#2685 - Zeichnen eines Kreises mittels imagearc
  • Example#2686 - Saving a BMP file
  • Example#2687 - imagechar-Beispiel
  • Example#2688 - imagecharup-Beispiel
  • Example#2689 - imagecolorallocate-Beispiel
  • Example#2690 - Example of using imagecolorallocatealpha
  • Example#2691 - Convert typical alpha values for use with imagecolorallocatealpha
  • Example#2692 - Zurgriff auf individuelle RGB-Werte
  • Example#2693 - Menschenlesbare RGB-Werte unter Verwendung von imagecolorsforindex
  • Example#2694 - Suche nach einem Satz von Farben in einem Bild
  • Example#2695 - Search for a set of colors in an image
  • Example#2696 - Example of using imagecolorclosesthwb
  • Example#2697 - Verwendung von imagecolordeallocate
  • Example#2698 - Ermittle Farben des GD-Logos
  • Example#2699 - Get colors from the GD logo
  • Example#2700 - imagecolormatch example
  • Example#2701 - Verwendung von imagecoloresolve, um Farben aus einem Bild auszulesen
  • Example#2702 - Using imagecoloresolvealpha to get colors from an image
  • Example#2703 - imagecolorset-Beispiel
  • Example#2704 - imagecolorsforindex-Beispiel
  • Example#2705 - Ermitteln der Gesamtanzahl von Farben in einem Bild unter Verwendung von imagecolorstotal
  • Example#2706 - imagecolortransparent-Beispiel
  • Example#2707 - Embossing the PHP.net logo
  • Example#2708 - Gaussian blur
  • Example#2709 - Beschneiden des PHP.net-Logos
  • Example#2710 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#2711 - imagecopymergegray usage
  • Example#2712 - Simple example
  • Example#2713 - Resampling an image proportionally
  • Example#2714 - Ein Bild skalieren
  • Example#2715 - Erzeugen eines neuen GD-Bild-Streams und Ausgabe des Bildes
  • Example#2716 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#2717 - imagecreatefromgd2 example
  • Example#2718 - imagecreatefromgd2part example
  • Example#2719 - imagecreatefromgd example
  • Example#2720 - Beispiel zur Behandlung von Fehlern beim Einlesen eines GIFs
  • Example#2721 - Beispiel für Fehlerbehandlung beim Laden eines JPEG
  • Example#2722 - Beispiel für Fehlerbehandlung beim Laden eines PNG
  • Example#2723 - imagecreatefromstring example
  • Example#2724 - Example to handle an error during loading of a WBMP
  • Example#2725 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#2726 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#2727 - Creating an image instance using imagecreatefromxpm
  • Example#2728 - Creating a new GD image stream and outputting an image.
  • Example#2729 - imagecrop example
  • Example#2730 - Proper handling of auto-cropping
  • Example#2731 - imagedashedline-Beispiel
  • Example#2732 - Alternative zu imagedashedline
  • Example#2733 - Verwendung von imagedestroy vor PHP 8.0.0
  • Example#2734 - imageellipse example
  • Example#2735 - imagefill-Beispiel
  • Example#2736 - Creating a 3D looking pie
  • Example#2737 - imagefilledellipse example
  • Example#2738 - imagefilledpolygon-Beispiel
  • Example#2739 - Beispiel für die Verwendung von imagefilledrectangle
  • Example#2740 - Füllen einer Ellipse mit einer Farbe
  • Example#2741 - imagefilter grayscale example
  • Example#2742 - imagefilter brightness example
  • Example#2743 - imagefilter colorize example
  • Example#2744 - imagefilter negate example
  • Example#2745 - imagefilter pixelate example
  • Example#2746 - imagefilter scatter example
  • Example#2747 - Flips an image vertically
  • Example#2748 - Flips the image horizontally
  • Example#2749 - Verwendung von imagefontheight mit integrierten Schriftarten
  • Example#2750 - Verwendung von imagefontheight mit imageloadfont
  • Example#2751 - Verwendung von imagefontwidth mit integrierten Schriftarten
  • Example#2752 - Verwendung von imagefontwidth mit imageloadfont
  • Example#2753 - imageftbbox example
  • Example#2754 - imagefttext example
  • Example#2755 - Die Verwendung von imagegammacorrect
  • Example#2756 - Outputting a GD2 image
  • Example#2757 - Saving a GD2 image
  • Example#2758 - Outputting a GD image
  • Example#2759 - Saving a GD image
  • Example#2760 - imagegetclip example
  • Example#2761 - Ein Bild mittels imagegif ausgeben
  • Example#2762 - Eine PNG-Datei mit imagegif in GIF konvertieren
  • Example#2763 - imagegrabscreen example
  • Example#2764 - imagegrabwindow example
  • Example#2765 - Aktiviere Interlacing unter Verendung von imageinterlace
  • Example#2766 - Simple detection of true color image instances using imageistruecolor
  • Example#2767 - Ein Bild an den Browser ausgeben
  • Example#2768 - Ein Bild in eine Datei speichern
  • Example#2769 - Das Bild mit 75% Qualität an den Browser ausgeben
  • Example#2770 - imagelayereffect example
  • Example#2771 - Zeichnen einer dicken Linie
  • Example#2772 - imageloadfont-Beispiel
  • Example#2773 - imageopenpolygon example
  • Example#2774 - imagepalettecopy example
  • Example#2775 - Converts any image object to true color
  • Example#2776 - imagepolygon-Beispiel
  • Example#2777 - Einfaches imagerectangle-Beispiel
  • Example#2778 - Setting and getting the resolution of an image
  • Example#2779 - Rotate an image 180 degrees
  • Example#2780 - Grundlegende Verwendung imagesavealpha-Verwendung
  • Example#2781 - imagesetbrush example
  • Example#2782 - imagesetinterpolation example
  • Example#2783 - imagesetpixel-Beispiel
  • Example#2784 - imagesetstyle example
  • Example#2785 - imagesetthickness example
  • Example#2786 - imagesettile example
  • Example#2787 - imagestring-Beispiel
  • Example#2788 - imagestringup-Beispiel
  • Example#2789 - Verwenden von imagesx
  • Example#2790 - Verwenden von imagesy
  • Example#2791 - Converting a true color image to a palette-based image
  • Example#2792 - imagettfbbox-Beispiel
  • Example#2793 - imagettftext-Beispiel
  • Example#2794 - Prüfe PNG-Unterstützung
  • Example#2795 - Outputting a WBMP image
  • Example#2796 - Saving the WBMP image
  • Example#2797 - Outputting the image with a different foreground
  • Example#2798 - Saving an WebP file
  • Example#2799 - Saving an XBM file
  • Example#2800 - Saving an XBM file with a different foreground color
  • Example#2801 - Embedding IPTC data into a JPEG
  • Example#2802 - iptcparse() used together with getimagesize
  • Example#2803 - jpeg2wbmp-Beispiel
  • Example#2804 - png2wbmp example
  • Example#2805 - Gmagick Example
  • Example#2806 - Gmagick::despeckleimage example
  • Example#2807 - Gmagick::setCompressionQuality
  • Example#2808 - Creating a thumbnail in Imagick
  • Example#2809 - Make a thumbnail of all JPG files in a directory
  • Example#2810 - Creating a reflection of an image
  • Example#2811 - Filling text with gradient
  • Example#2812 - Read in GIF image and resize all frames
  • Example#2813 - Create a PHP logo
  • Example#2814 - Using Imagick::adaptiveBlurImage:
  • Example#2815 - Using Imagick::adaptiveResizeImage
  • Example#2816 - A Imagick::adaptiveSharpenImage example
  • Example#2817 - Imagick::adaptiveThresholdImage
  • Example#2818 - Imagick::addNoiseImage
  • Example#2819 - Imagick::affineTransformImage
  • Example#2820 - Using Imagick::annotateImage:
  • Example#2821 - Imagick::appendImages example
  • Example#2822 - Imagick::autoLevelImage
  • Example#2823 - Imagick::blackThresholdImage
  • Example#2824 - Imagick::blueShiftImage
  • Example#2825 - Using Imagick::blurImage:
  • Example#2826 - Imagick::borderImage
  • Example#2827 - Imagick::brightnessContrastImage
  • Example#2828 - Imagick::charcoalImage
  • Example#2829 - Using Imagick::chopImage:
  • Example#2830 - Imagick object cloning in different versions of imagick
  • Example#2831 - Using Imagick::clutImage:
  • Example#2832 - Imagick::colorizeImage
  • Example#2833 - Imagick::colorMatrixImage
  • Example#2834 - Using Imagick::commentImage:
  • Example#2835 - Using Imagick::compareImageLayers
  • Example#2836 - Using Imagick::compareImages:
  • Example#2837 - Using Imagick::compositeImage:
  • Example#2838 - Imagick::contrastImage
  • Example#2839 - Imagick::convolveImage
  • Example#2840 - Imagick::cropImage
  • Example#2841 - Imagick::deskewImage
  • Example#2842 - Imagick::despeckleImage
  • Example#2843 - Using Imagick::distortImage:
  • Example#2844 - Imagick::edgeImage
  • Example#2845 - Imagick::embossImage
  • Example#2846 - Imagick::enhanceImage
  • Example#2847 - Imagick::equalizeImage
  • Example#2848 - Using Imagick::evaluateImage
  • Example#2849 - Using Imagick::exportImagePixels
  • Example#2850 - Imagick::filter
  • Example#2851 - Imagick::flipImage
  • Example#2852 - Imagick::floodfillPaintImage example
  • Example#2853 - Imagick::flopImage
  • Example#2854 - Imagick::forwardFourierTransformImage
  • Example#2855 - Imagick::frameImage
  • Example#2856 - Create a sinusoidal gradient
  • Example#2857 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#2858 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#2859 - Imagick::fxImage
  • Example#2860 - Imagick::gammaImage
  • Example#2861 - Imagick::gaussianBlurImage
  • Example#2862 - Using Imagick::getImageGeometry
  • Example#2863 - Generates Imagick::getImageHistogram
  • Example#2864 - Using Imagick::getImageLength:
  • Example#2865 - Using Imagick::getImageProperties:
  • Example#2866 - Using Imagick::getImageProperty:
  • Example#2867 - Using Imagick::getIteratorIndex:
  • Example#2868 - Imagick::getPixelIterator
  • Example#2869 - Imagick::getPixelRegionIterator example
  • Example#2870 - Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)
  • Example#2871 - Imagick::haldClutImage
  • Example#2872 - Imagick::identifyFormat
  • Example#2873 - Example Result Format
  • Example#2874 - Imagick::implodeImage
  • Example#2875 - Imagick::importImagePixels example
  • Example#2876 - Imagick::levelImage
  • Example#2877 - Imagick::linearStretchImage
  • Example#2878 - Imagick::magnifyImage
  • Example#2879 - Imagick::medianFilterImage
  • Example#2880 - Imagick::mergeImageLayers
  • Example#2881 - Imagick::modulateImage
  • Example#2882 - Convolve Imagick::morphology
  • Example#2883 - Correlate Imagick::morphology
  • Example#2884 - Erode Imagick::morphology
  • Example#2885 - Erode Intensity Imagick::morphology
  • Example#2886 - Dilate Imagick::morphology
  • Example#2887 - Dilate intensity Imagick::morphology
  • Example#2888 - Distance with Chebyshev kernel Imagick::morphology
  • Example#2889 - Distance with Manhattan kernel Imagick::morphology
  • Example#2890 - Distance with ocatagonal kernel Imagick::morphology
  • Example#2891 - Distance with Euclidean kernel Imagick::morphology
  • Example#2892 - Edge Imagick::morphology
  • Example#2893 - Open Imagick::morphology
  • Example#2894 - Open intensity Imagick::morphology
  • Example#2895 - Close Imagick::morphology
  • Example#2896 - Close Intensity Imagick::morphology
  • Example#2897 - Smooth Imagick::morphology
  • Example#2898 - Edge in Imagick::morphology
  • Example#2899 - Edge out Imagick::morphology
  • Example#2900 - 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#2901 - 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#2902 - Hit and Miss Imagick::morphology
  • Example#2903 - Thinning Imagick::morphology
  • Example#2904 - Thicken Imagick::morphology
  • Example#2905 - Thick to generate a convex hull Imagick::morphology
  • Example#2906 - Iterative morphology Imagick::morphology
  • Example#2907 - Helper function to get an image silhouette Imagick::morphology
  • Example#2908 - Imagick::motionBlurImage
  • Example#2909 - Imagick::negateImage
  • Example#2910 - Using Imagick::newImage:
  • Example#2911 - Imagick::newPseudoImage
  • Example#2912 - Imagick::normalizeImage
  • Example#2913 - Imagick::oilPaintImage
  • Example#2914 - Using Imagick::optimizeImageLayers
  • Example#2915 - Imagick::orderedPosterizeImage
  • Example#2916 - Using Imagick::pingImageBlob
  • Example#2917 - Using Imagick::pingImageFile
  • Example#2918 - A Imagick::polaroidImage example
  • Example#2919 - Imagick::posterizeImage
  • Example#2920 - Imagick::quantizeImage
  • Example#2921 - Using Imagick::queryFontMetrics:
  • Example#2922 - Imagick::queryFonts
  • Example#2923 - Imagick::queryFormats
  • Example#2924 - Imagick::radialBlurImage
  • Example#2925 - Imagick::raiseImage
  • Example#2926 - Imagick::randomThresholdImage
  • Example#2927 - Imagick::readImageBlob
  • Example#2928 - Imagick::recolorImage
  • Example#2929 - Imagick::reduceNoiseImage
  • Example#2930 - Imagick::resampleImage
  • Example#2931 - Imagick::resizeImage
  • Example#2932 - Imagick::rollImage
  • Example#2933 - Imagick::rotateImage
  • Example#2934 - Imagick::rotationalBlurImage
  • Example#2935 - Using Imagick::roundCorners:
  • Example#2936 - Imagick::scaleImage
  • Example#2937 - Imagick::segmentImage
  • Example#2938 - Imagick::selectiveBlurImage
  • Example#2939 - Imagick::separateImageChannel
  • Example#2940 - Imagick::sepiaToneImage
  • Example#2941 - Imagick::setCompressionQuality
  • Example#2942 - A Imagick::setFont example
  • Example#2943 - A Imagick::setImage example
  • Example#2944 - Imagick::setImageArtifact
  • Example#2945 - Imagick::setImageBias
  • Example#2946 - Imagick::setImageClipMask
  • Example#2947 - Imagick::setImageCompressionQuality
  • Example#2948 - Modify animated Gif with Imagick::setImageDelay
  • Example#2949 - Basic Imagick::setImageIterations usage
  • Example#2950 - A Imagick::setImageOpacity example
  • Example#2951 - Imagick::setImageOrientation
  • Example#2952 - Using Imagick::setImageProperty:
  • Example#2953 - Imagick::setImageResolution
  • Example#2954 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#2955 - Using Imagick::setIteratorIndex:
  • Example#2956 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#2957 - Imagick::setOption
  • Example#2958 - Imagick::setOption
  • Example#2959 - A Imagick::setPointSize example
  • Example#2960 - Imagick::setProgressMonitor
  • Example#2961 - Imagick::setSamplingFactors
  • Example#2962 - Imagick::shadeImage
  • Example#2963 - Imagick::shadowImage
  • Example#2964 - Imagick::sharpenImage
  • Example#2965 - Imagick::shaveImage
  • Example#2966 - Imagick::shearImage
  • Example#2967 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#2968 - Imagick::sketchImage
  • Example#2969 - Imagick::smushImages
  • Example#2970 - Imagick::solarizeImage
  • Example#2971 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2972 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#2973 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#2974 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#2975 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2976 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#2977 - Imagick::spliceImage
  • Example#2978 - Imagick::spreadImage
  • Example#2979 - Imagick::statisticImage
  • Example#2980 - Imagick::subImageMatch
  • Example#2981 - Imagick::swirlImage
  • Example#2982 - Imagick::textureImage
  • Example#2983 - Imagick::thresholdImage
  • Example#2984 - Imagick::thumbnailImage
  • Example#2985 - Imagick::tintImage
  • Example#2986 - Using Imagick::transformImage:
  • Example#2987 - Imagick::transformImageColorspace example
  • Example#2988 - Imagick::transparentPaintImage
  • Example#2989 - Imagick::transposeImage
  • Example#2990 - Imagick::transverseImage
  • Example#2991 - Using Imagick::trimImage:
  • Example#2992 - Imagick::uniqueImageColors
  • Example#2993 - Imagick::unsharpMaskImage
  • Example#2994 - Imagick::vignetteImage
  • Example#2995 - WaveImage can be quite slow Imagick::waveImage
  • Example#2996 - Imagick::whiteThresholdImage
  • Example#2997 - ImagickDraw::affine example
  • Example#2998 - ImagickDraw::arc example
  • Example#2999 - ImagickDraw::bezier example
  • Example#3000 - ImagickDraw::circle example
  • Example#3001 - ImagickDraw::composite example
  • Example#3002 - ImagickDraw::ellipse example
  • Example#3003 - ImagickDraw::line example
  • Example#3004 - ImagickDraw::matte example
  • Example#3005 - ImagickDraw::pathCurveToQuadraticBezierAbsolute example
  • Example#3006 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute example
  • Example#3007 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative example
  • Example#3008 - ImagickDraw::pathStart example
  • Example#3009 - ImagickDraw::point example
  • Example#3010 - ImagickDraw::polygon example
  • Example#3011 - ImagickDraw::polyline example
  • Example#3012 - ImagickDraw::popDefs example
  • Example#3013 - ImagickDraw::push example
  • Example#3014 - ImagickDraw::pushPattern example
  • Example#3015 - ImagickDraw::rectangle example
  • Example#3016 - ImagickDraw::rotate example
  • Example#3017 - ImagickDraw::roundRectangle example
  • Example#3018 - ImagickDraw::scale example
  • Example#3019 - ImagickDraw::setClipPath example
  • Example#3020 - ImagickDraw::setClipRule example
  • Example#3021 - ImagickDraw::setClipUnits example
  • Example#3022 - ImagickDraw::setFillAlpha example
  • Example#3023 - ImagickDraw::setFillColor
  • Example#3024 - ImagickDraw::setFillOpacity
  • Example#3025 - ImagickDraw::setFillRule example
  • Example#3026 - ImagickDraw::setFont example
  • Example#3027 - ImagickDraw::setFontFamily example
  • Example#3028 - ImagickDraw::setFontSize example
  • Example#3029 - ImagickDraw::setFontStretch example
  • Example#3030 - ImagickDraw::setFontStyle example
  • Example#3031 - ImagickDraw::setFontWeight example
  • Example#3032 - ImagickDraw::setGravity example
  • Example#3033 - ImagickDraw::setStrokeAlpha example
  • Example#3034 - ImagickDraw::setStrokeAntialias example
  • Example#3035 - ImagickDraw::setStrokeColor example
  • Example#3036 - ImagickDraw::setStrokeDashArray example
  • Example#3037 - ImagickDraw::setStrokeDashOffset example
  • Example#3038 - ImagickDraw::setStrokeLineCap example
  • Example#3039 - ImagickDraw::setStrokeLineJoin example
  • Example#3040 - ImagickDraw::setStrokeMiterLimit example
  • Example#3041 - ImagickDraw::setStrokeOpacity example
  • Example#3042 - ImagickDraw::setStrokeWidth example
  • Example#3043 - ImagickDraw::setTextAlignment example
  • Example#3044 - ImagickDraw::setTextAntialias example
  • Example#3045 - ImagickDraw::setTextDecoration example
  • Example#3046 - ImagickDraw::setTextUnderColor example
  • Example#3047 - ImagickDraw::setVectorGraphics example
  • Example#3048 - ImagickDraw::setViewBox example
  • Example#3049 - ImagickDraw::skewX example
  • Example#3050 - ImagickDraw::skewY example
  • Example#3051 - ImagickDraw::translate example
  • Example#3052 - ImagickPixel::construct
  • Example#3053 - Basic Imagick::getColor usage
  • Example#3054 - Basic Imagick::getColorAsString usage
  • Example#3055 - ImagickPixel getColorCount
  • Example#3056 - Basic Imagick::getColorValue usage
  • Example#3057 - ImagickPixel::getColorValueQuantum
  • Example#3058 - Basic Imagick::getHSL example
  • Example#3059 - ImagickPixel::isSimilar
  • Example#3060 - ImagickPixel::setColor
  • Example#3061 - Basic Imagick::setColorValue usage
  • Example#3062 - ImagickPixel::setColorValueQuantum
  • Example#3063 - Use ImagickPixel::setHSL to modify a color
  • Example#3064 - ImagickPixelIterator::clear
  • Example#3065 - ImagickPixelIterator::construct
  • Example#3066 - ImagickPixelIterator::getNextIteratorRow
  • Example#3067 - ImagickPixelIterator::resetIterator
  • Example#3068 - ImagickPixelIterator::setIteratorRow
  • Example#3069 - ImagickKernel::addKernel
  • Example#3070 - ImagickKernel::addUnityKernel
  • Example#3071 - ImagickKernel::addUnityKernel
  • Example#3072 - ImagickKernel::fromBuiltin
  • Example#3073 - ImagickKernel::fromMatrix
  • Example#3074 - ImagickKernel::getMatrix
  • Example#3075 - ImagickKernel::scale
  • Example#3076 - ImagickKernel::separate
  • Example#3077 - imap_append-Beispiel
  • Example#3078 - imap_check-Beispiel
  • Example#3079 - imap_createmailbox-Beispiel
  • Example#3080 - imap_delete-Beispiel
  • Example#3081 - imap_fetch_overview-Beispiel
  • Example#3082 - imap_gc-Beispiel
  • Example#3083 - imap_get_quota-Beispiel
  • Example#3084 - Beispiel für imap_get_quota ab 4.3 und aufwärts
  • Example#3085 - imap_get_quotaroot-Beispiel
  • Example#3086 - imap_getacl-Beispiel
  • Example#3087 - imap_getmailboxes-Beispiel
  • Example#3088 - imap_is_open example
  • Example#3089 - imap_list-Beispiel
  • Example#3090 - imap_mail_compose-Beispiel
  • Example#3091 - imap_mailboxmsginfo-Beispiel
  • Example#3092 - imap_mime_header_decode-Beispiel
  • Example#3093 - Verschiedene imap_open-Aufrufe
  • Example#3094 - imap_open-Beispiel
  • Example#3095 - imap_ping-Beispiel
  • Example#3096 - imap_reopen-Beispiel
  • Example#3097 - imap_rfc822_parse_adrlist-Beispiel
  • Example#3098 - imap_rfc822_write_address-Beispiel
  • Example#3099 - imap_search-Beispiel
  • Example#3100 - imap_set_quota-Beispiel
  • Example#3101 - imap_setflag_full-Beispiel
  • Example#3102 - imap_status-Beispiel
  • Example#3103 - imap_thread-Beispiel
  • Example#3104 - imap_timeout-Beispiel
  • Example#3105 - Die grundlegende imap_utf8-Verwendung
  • Example#3106 - Hash-Wert berechnen und einen Benutzer hinzufügen
  • Example#3107 - Verschicken einer E-Mail
  • Example#3108 - Verschicken einer E-Mail mit zusätzlichen Headern
  • Example#3109 - Verschicken einer E-Mail mit zusätzliche Headern als Array
  • Example#3110 - Verschicken einer E-Mail mit einem zusätzlichen Kommandozeilen-Parameter
  • Example#3111 - Verschicken einer HTML-E-Mail.
  • Example#3112 - mailparse_determine_best_xfer_encoding example
  • Example#3113 - mailparse_rfc822_parse_addresses example
  • Example#3114 - mailparse_stream_encode example
  • Example#3115 - mailparse_uudecode_all example
  • Example#3116 - bcadd-Beispiel
  • Example#3117 - bccomp-Beispiel
  • Example#3118 - bcdiv-Beispiel
  • Example#3119 - bcmod-Beispiel
  • Example#3120 - bcmod mit Dezimalzahlen
  • Example#3121 - bcmul-Beispiel
  • Example#3122 - bcmul-Nachkommastellen-Beispiel
  • Example#3123 - bcpow-Beispiel
  • Example#3124 - bcpow Genauigkeitsbeispiel
  • Example#3125 - bcscale-Beispiel
  • Example#3126 - bcsqrt-Beispiel
  • Example#3127 - bcsub-Beispiel
  • Example#3128 - Fakultätsfunktion unter Verwendung von GMP
  • Example#3129 - gmp_abs example
  • Example#3130 - gmp_add example
  • Example#3131 - gmp_and example
  • Example#3132 - gmp_clrbit example
  • Example#3133 - gmp_cmp example
  • Example#3134 - gmp_com example
  • Example#3135 - gmp_div_q example
  • Example#3136 - Division of GMP numbers
  • Example#3137 - gmp_div_r example
  • Example#3138 - gmp_divexact example
  • Example#3139 - gmp_export example
  • Example#3140 - gmp_fact example
  • Example#3141 - gmp_gcd example
  • Example#3142 - Solving a linear Diophantine equation
  • Example#3143 - gmp_hamdist example
  • Example#3144 - gmp_import example
  • Example#3145 - Creating GMP number
  • Example#3146 - gmp_intval example
  • Example#3147 - gmp_invert example
  • Example#3148 - gmp_jacobi example
  • Example#3149 - gmp_legendre example
  • Example#3150 - gmp_mod example
  • Example#3151 - gmp_mul example
  • Example#3152 - gmp_neg example
  • Example#3153 - gmp_nextprime example
  • Example#3154 - gmp_or example
  • Example#3155 - gmp_perfect_square example
  • Example#3156 - gmp_popcount example
  • Example#3157 - gmp_pow example
  • Example#3158 - gmp_powm example
  • Example#3159 - gmp_prob_prime example
  • Example#3160 - gmp_random_bits example
  • Example#3161 - gmp_random_range example
  • Example#3162 - gmp_random_seed example
  • Example#3163 - gmp_random example
  • Example#3164 - gmp_scan0 example
  • Example#3165 - gmp_scan1 example
  • Example#3166 - gmp_setbit example - 0 index
  • Example#3167 - gmp_setbit example - 1 index
  • Example#3168 - gmp_setbit example - clearing a bit
  • Example#3169 - gmp_sign example
  • Example#3170 - gmp_sqrt example
  • Example#3171 - gmp_sqrtrem example
  • Example#3172 - Converting a GMP number to a string
  • Example#3173 - gmp_sub example
  • Example#3174 - gmp_testbit example
  • Example#3175 - gmp_xor example
  • Example#3176 - abs-Beispiel
  • Example#3177 - base_convert-Beispiel
  • Example#3178 - bindec-Beispiel
  • Example#3179 - bindec interpretiert die Eingabe als vorzeichenlose Ganzzahlen
  • Example#3180 - ceil-Beispiel
  • Example#3181 - cos-Beispiel
  • Example#3182 - decbin-Beispiel
  • Example#3183 - dechex-Beispiel
  • Example#3184 - dechex-Beispiel mit großen Ganzzahlen
  • Example#3185 - decoct-Beispiel
  • Example#3186 - deg2rad-Beispiel
  • Example#3187 - exp-Beispiel
  • Example#3188 - Beispiel für die Verwendung von fdiv
  • Example#3189 - floor-Beispiel
  • Example#3190 - fmod-Beispiel
  • Example#3191 - hexdec-Beispiel
  • Example#3192 - intdiv-Beispiel
  • Example#3193 - is_finite-Beispiel
  • Example#3194 - is_infinite-Beispiel
  • Example#3195 - is_nan-Beispiel
  • Example#3196 - Beispiel für die Verwendung von max
  • Example#3197 - Beispiel für die Verwendung von min
  • Example#3198 - octdec-Beispiel
  • Example#3199 - pi-Beispiel
  • Example#3200 - Einige pow-Beispiele
  • Example#3201 - rad2deg-Beispiel
  • Example#3202 - round-Beispiele
  • Example#3203 - Wie precision eine Gleitkommazahl betrifft
  • Example#3204 - mode-Beispiele
  • Example#3205 - Beispiele für mode mit precision
  • Example#3206 - sin-Beispiel
  • Example#3207 - sqrt-Beispiel
  • Example#3208 - tan-Beispiel
  • Example#3209 - Auswertung eines FDF_Dokuments
  • Example#3210 - JavaScript-Code zu einem FDF hinzufügen
  • Example#3211 - Füllen von Formularwerten in einem PDF Dokument
  • Example#3212 - Storing an uploaded file
  • Example#3213 - Alle Feldnamen in einem FDF ermitteln
  • Example#3214 - Accessing the form data
  • Example#3215 - Zugang zu den Formulardaten
  • Example#3216 - Retrieving FDF as a string
  • Example#3217 - FDF-Daten an ein zweites Formular übergeben
  • Example#3218 - Erstellen einer Klatext-Signatur mit gnupg (prozedural)
  • Example#3219 - Erstellen einer Klatext-Signatur mit gnupg (objektorientiert)
  • Example#3220 - keylistiterator
  • Example#3221 - Verwendungsbeispiel gnupg_adddecryptkey
  • Example#3222 - OO gnupg_adddecryptkey Beispiel
  • Example#3223 - Prozedurales gnupg_addencryptkey Beispiel
  • Example#3224 - OO (objektorientiertes) gnupg_addencryptkey-Beispiel
  • Example#3225 - Prozedurales gnupg_addsignkey Beispiel
  • Example#3226 - OO (objektorientiertes) gnupg_addsignkey-Beispiel
  • Example#3227 - Prozedurales gnupg_cleardecryptkeys Beispiel
  • Example#3228 - OO (objektorientiertes) gnupg_cleardecryptkeys Beispiel
  • Example#3229 - Prozedurales gnupg_clearencryptkeys Beispiel
  • Example#3230 - OO (objektorientiertes) gnupg_clearencryptkeys Beispiel
  • Example#3231 - Prozedurales gnupg_clearsignkeys Beispiel
  • Example#3232 - OO (objektorientiertes) gnupg_clearsignkeys Beispiel
  • Example#3233 - Prozedurales gnupg_decrypt-Beispiel
  • Example#3234 - OO (objektorientiertes)gnupg_decrypt-Beispiel
  • Example#3235 - Prozedurales gnupg_decryptverify-Beispiel
  • Example#3236 - OO (objektorientiertes) gnupg_decryptverify-Beispiel
  • Example#3237 - Prozedurales gnupg_deletekey-Beispiel
  • Example#3238 - Objektorientiertes gnupg_deletekey-Beispiel
  • Example#3239 - Prozedurales gnupg_encrypt-Beispiel
  • Example#3240 - OO (objektorientiertes) gnupg_encrypt-Beispiele
  • Example#3241 - Prozedurales gnupg_encryptsign-Beispiel
  • Example#3242 - OO (objektorientiertes) gnupg_encryptsign-Beispiel
  • Example#3243 - Prozedurales gnupg_export-Beispiel
  • Example#3244 - OO (objektorientiertes) gnupg_export-Beispiel
  • Example#3245 - Prozedurales gnupg_getengineinfo-Beispiel
  • Example#3246 - Objektorientiertes gnupg_getengineinfo-Beispiel
  • Example#3247 - Prozedurales gnupg_geterror-Beispiel
  • Example#3248 - OO (objektorientiertes) gnupg_geterror-Beispiel
  • Example#3249 - Prozedurales gnupg_geterrorinfo-Beispiel
  • Example#3250 - Objektorientiertes gnupg_geterrorinfo-Beispiel
  • Example#3251 - Prozedurales gnupg_getprotocol Beispiel
  • Example#3252 - OO (objektorientiertes) gnupg_getprotocol Beispiel
  • Example#3253 - Prozedurales gnupg_gettrustlist-Beispiel
  • Example#3254 - Objektorientiertes gnupg_gettrustlist-Beispiel
  • Example#3255 - Prozedurales gnupg_import-Beispiel
  • Example#3256 - OO (objektorientiertes) gnupg_import-Beispiel
  • Example#3257 - Prozedurales gnupg_init-Beispiel mit Standardeinstellung
  • Example#3258 - Prozedurales gnupg_init-Beispiel mit geänderten Dateinamen und Home-Verzeichnis
  • Example#3259 - OO (objektorientiertes) gnupg-Initialisierungsbeispiel mit Standardeinstellung
  • Example#3260 - OO gnupg-Initialisierungsbeispiel mit geänderten Dateinamen und Home-Verzeichnis
  • Example#3261 - Prozedurales gnupg_keyinfo-Beispiel
  • Example#3262 - OO (objektorientiertes) gnupg_keyinfo-Beispiel
  • Example#3263 - Prozedurales gnupg_listsignatures-Beispiel
  • Example#3264 - Objektorientiertes gnupg_listsignatures-Beispiel
  • Example#3265 - Prozedurales gnupg_setarmor Beispiel
  • Example#3266 - OO (objektorientiertes) gnupg_setarmor Beispiel
  • Example#3267 - Procedurales gnupg_seterrormode Beispiel
  • Example#3268 - OO (objektorientiertes) gnupg_seterrormode Beispiel
  • Example#3269 - Prozedurales gnupg_setsignmode Beispiel
  • Example#3270 - OO gnupg_setsignmode Beispiel
  • Example#3271 - Prozedurales gnupg_sign-Beispiel
  • Example#3272 - OO gnupg_sign-Beispiel
  • Example#3273 - Prozedurales gnupg_verify-Beispiel
  • Example#3274 - OO gnupg_verify-Beispiel
  • Example#3275 - Creating and using a pattern
  • Example#3276 - Creating and using a template
  • Example#3277 - Hyphennate a text
  • Example#3278 - Drawing a rectangle
  • Example#3279 - Creating and using a spot color
  • Example#3280 - Rotation of the coordinate system
  • Example#3281 - Placing text at a given position
  • Example#3282 - Drawing a dashed line
  • Example#3283 - Translation of the coordinate system
  • Example#3284 - A rpmdbinfo example
  • Example#3285 - Searching for the package owning a file
  • Example#3286 - A rpminfo example
  • Example#3287 - example
  • Example#3288 - example
  • Example#3289 - example
  • Example#3290 - example
  • Example#3291 - example
  • Example#3292 - example
  • Example#3293 - example
  • Example#3294 - example
  • Example#3295 - example
  • Example#3296 - example
  • Example#3297 - example
  • Example#3298 - example
  • Example#3299 - example
  • Example#3300 - setColumn example
  • Example#3301 - setRow example
  • Example#3302 - Align style example
  • Example#3303 - Bold style example
  • Example#3304 - Italic style example
  • Example#3305 - Underline style example
  • Example#3306 - Incorrect requests
  • Example#3307 - Calling request from a request callback
  • Example#3308 - Calling request from a request callback
  • Example#3309 - Using eio with libevent
  • Example#3310 - Cancelling a request
  • Example#3311 - Calling eio_chmod
  • Example#3312 - Making a custom request
  • Example#3313 - Grouping requests
  • Example#3314 - Using eio with libevent extension
  • Example#3315 - Using eio with event extension
  • Example#3316 - eio_cancel example
  • Example#3317 - eio_custom example
  • Example#3318 - eio_event_loop example
  • Example#3319 - eio_lstat example
  • Example#3320 - Using eio with libevent
  • Example#3321 - Grouping requests
  • Example#3322 - eio_grp example
  • Example#3323 - eio_link example
  • Example#3324 - eio_lstat example
  • Example#3325 - eio_mkdir example
  • Example#3326 - eio_mknod example
  • Example#3327 - eio_nreqs example
  • Example#3328 - eio_open example
  • Example#3329 - eio_poll example
  • Example#3330 - eio_read example
  • Example#3331 - eio_readdir example
  • Example#3332 - eio_readlink example
  • Example#3333 - eio_realpath example
  • Example#3334 - eio_rename example
  • Example#3335 - eio_rmdir example
  • Example#3336 - eio_stat example
  • Example#3337 - eio_statvfs example
  • Example#3338 - eio_symlink example
  • Example#3339 - Simple timers
  • Example#3340 - Periodic timer. Tick each 10.5 seconds
  • Example#3341 - Periodic timer. Use reschedule callback
  • Example#3342 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3343 - Wait until STDIN is readable
  • Example#3344 - Use some async I/O to access a socket
  • Example#3345 - Embedding one loop into another
  • Example#3346 - Embedding loop created with kqueue backend into the default loop
  • Example#3347 - Handle SIGTERM signal
  • Example#3348 - Monitor changes of /var/log/messages
  • Example#3349 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3350 - Process status changes
  • Example#3351 - Using reschedule callback
  • Example#3352 - Embedding loop created with kqueue backend into the default loop
  • Example#3353 - Embedding one loop into another
  • Example#3354 - Embedding loop created with kqueue backend into the default loop
  • Example#3355 - Embedding loop created with kqueue backend into the default loop
  • Example#3356 - Periodic timer. Use reschedule callback
  • Example#3357 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3358 - Hourly watcher
  • Example#3359 - Handle SIGTERM signal
  • Example#3360 - Monitor changes of /var/log/messages
  • Example#3361 - Monitor changes of /var/log/messages
  • Example#3362 - Simple timers
  • Example#3363 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3364 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3365 - Expect Usage Example
  • Example#3366 - Another Expect Usage Example
  • Example#3367 - expect_expectl example
  • Example#3368 - expect_popen example
  • Example#3369 - Prozesskontrollbeispiel
  • Example#3370 - pcntl_fork-Beispiel
  • Example#3371 - pcntl_rfork example
  • Example#3372 - pcntl_signal_dispatch example
  • Example#3373 - pcntl_signal_get_handler example
  • Example#3374 - pcntl_signal-Beispiel
  • Example#3375 - pcntl_sigprocmask example
  • Example#3376 - pcntl_sigwaitinfo example
  • Example#3377 - posix_access-Beispiel
  • Example#3378 - posix_ctermid-Beispiel
  • Example#3379 - posix_eaccess-Beispiel
  • Example#3380 - posix_fpathconf-Beispiel
  • Example#3381 - posix_get_last_error-Beispiel
  • Example#3382 - posix_getcwd-Beispiel
  • Example#3383 - posix_getegid-Beispiel
  • Example#3384 - posix_geteuid-Beispiel
  • Example#3385 - posix_getgid-Beispiel
  • Example#3386 - Beispiel zur Verwendung von posix_getgrgid
  • Example#3387 - Beispiel für die Verwendung von posix_getgrnam
  • Example#3388 - posix_getgroups-Beispiel
  • Example#3389 - posix_getlogin-Beispiel
  • Example#3390 - posix_getpgid-Beispiel
  • Example#3391 - posix_getpid-Beispiel
  • Example#3392 - posix_getppid-Beispiel
  • Example#3393 - posix_getpwnam-Beispiel
  • Example#3394 - posix_getpwuid-Beispiel
  • Example#3395 - posix_getrlimit-Beispiel
  • Example#3396 - posix_getsid-Beispiel
  • Example#3397 - posix_getuid-Beispiel
  • Example#3398 - posix_mknod-Beispiel
  • Example#3399 - posix_pathconf-Beispiel
  • Example#3400 - posix_setegid-Beispiel
  • Example#3401 - posix_setgid-Beispiel
  • Example#3402 - posix_setuid-Beispiel
  • Example#3403 - posix_strerror-Beispiel
  • Example#3404 - posix_sysconf-Beispiel
  • Example#3405 - posix_times-Beispiel
  • Example#3406 - posix_uname-Beispiel
  • Example#3407 - escapeshellarg-Beispiel
  • Example#3408 - escapeshellcmd-Beispiel
  • Example#3409 - Ein exec-Beispiel
  • Example#3410 - Verwendung von proc_nice, um die Prozesspriorität auf hoch zu setzen
  • Example#3411 - Ein proc_open-Beispiel
  • Example#3412 - proc_open-Eigenheit unter Windows
  • Example#3413 - Ein shell_exec-Beispiel
  • Example#3414 - system example
  • Example#3415 - Example showing Future as return value
  • Example#3416 - Example showing Future as synchronization point
  • Example#3417 - Fetch a chunk of the property table
  • Example#3418 - Counting the properties of an object
  • Example#3419 - Runtime inheritance
  • Example#3420 - Detect the state of the referenced object
  • Example#3421 - Detect the state of the referenced object
  • Example#3422 - Merging into the property table of a threaded object
  • Example#3423 - Notifications and Waiting
  • Example#3424 - Notifications and Waiting
  • Example#3425 - Popping the last item from the property table of a threaded object
  • Example#3426 - Shifting the first item from the property table of a threaded object
  • Example#3427 - Synchronizing
  • Example#3428 - Notifications and Waiting
  • Example#3429 - Return the identity of the Thread or Process that created the referenced Thread
  • Example#3430 - Return the currently executing Thread
  • Example#3431 - Return the identity of the currently executing Thread
  • Example#3432 - Return the identity of the referenced Thread
  • Example#3433 - Detect the state of the referenced Thread
  • Example#3434 - Tell if the referenced Thread was started
  • Example#3435 - Join with the referenced Thread
  • Example#3436 - Starting Threads
  • Example#3437 - A basic example of Worker::collect
  • Example#3438 - A basic example of Worker::getStacked
  • Example#3439 - Detect the state of a worker
  • Example#3440 - Shutdown the referenced worker
  • Example#3441 - Stacking a task for execution onto a worker
  • Example#3442 - Removing objects from the stack of Workers
  • Example#3443 - A basic example of Pool::collect
  • Example#3444 - Creating Pools
  • Example#3445 - Shutting down a pool
  • Example#3446 - Submitting Tasks
  • Example#3447 - Submitting tasks to a specific worker
  • Example#3448 - New immutability semantics of Threaded
  • Example#3449 - Volatile use-case
  • Example#3450 - Shared Memory Operationen - Übersicht
  • Example#3451 - Einen gemeinsamen Speicherbereich schließen
  • Example#3452 - Einen gemeinsamen Speicherbereich löschen
  • Example#3453 - Einen neuen gemeinsamen Speicherbereich erstellen
  • Example#3454 - Aus dem gemeinsamen Speicherbereich lesen
  • Example#3455 - Die Größe des gemeinsamen Speicherbereichs ermitteln
  • Example#3456 - In den gemeinsamen Speicherbereich schreiben
  • Example#3457 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3458 - SyncMutex::__construct unnamed mutex example
  • Example#3459 - SyncMutex::lock example
  • Example#3460 - SyncMutex::unlock example
  • Example#3461 - SyncSemaphore::__construct example
  • Example#3462 - SyncSemaphore::lock example
  • Example#3463 - SyncSemaphore::unlock example
  • Example#3464 - SyncEvent::__construct example
  • Example#3465 - SyncEvent::fire example
  • Example#3466 - SyncEvent::reset example
  • Example#3467 - SyncEvent::wait example
  • Example#3468 - SyncReaderWriter::__construct example
  • Example#3469 - SyncReaderWriter::readlock example
  • Example#3470 - SyncReaderWriter::readunlock example
  • Example#3471 - SyncReaderWriter::writelock example
  • Example#3472 - SyncReaderWriter::writeunlock example
  • Example#3473 - SyncSharedMemory::__construct example
  • Example#3474 - SyncSharedMemory::first example
  • Example#3475 - SyncSharedMemory::__construct example
  • Example#3476 - SyncSharedMemory::size example
  • Example#3477 - SyncSharedMemory::write example
  • Example#3478 - A geoip_asnum_by_name example
  • Example#3479 - A geoip_continent_code_by_name example
  • Example#3480 - A geoip_country_code_by_name example
  • Example#3481 - A geoip_country_code3_by_name example
  • Example#3482 - A geoip_country_name_by_name example
  • Example#3483 - A geoip_database_info example
  • Example#3484 - A geoip_db_avail example
  • Example#3485 - A geoip_db_filename example
  • Example#3486 - A geoip_db_get_all_info example
  • Example#3487 - A geoip_db_get_all_info example
  • Example#3488 - A geoip_domain_by_name example
  • Example#3489 - A geoip_id_by_name example
  • Example#3490 - A geoip_isp_by_name example
  • Example#3491 - A geoip_netspeedcell_by_name example
  • Example#3492 - A geoip_org_by_name example
  • Example#3493 - A geoip_record_by_name example
  • Example#3494 - A geoip_region_by_name example
  • Example#3495 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#3496 - A geoip_region_name_by_code example using FIPS codes
  • Example#3497 - A geoip_setup_custom_directory example
  • Example#3498 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#3499 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#3500 - xor.data file
  • Example#3501 - Simple train
  • Example#3502 - Simple test
  • Example#3503 - fann_create_train_from_callback example
  • Example#3504 - fann_read_train_from_file example
  • Example#3505 - igbinary_serialize example
  • Example#3506 - Ein JsonSerializable::jsonSerialize-Beispiel, das ein Array zurückgibt.
  • Example#3507 - Ein JsonSerializable::jsonSerialize-Beispiel, das ein assoziatives Array zurückgibt.
  • Example#3508 - Ein JsonSerializable::jsonSerialize-Beispiel, das einen Integer zurückgibt.
  • Example#3509 - Ein JsonSerializable::jsonSerialize-Beispiel, das einen String zurückgibt
  • Example#3510 - json_decode-Beispiele
  • Example#3511 - Zugriff auf ungültige Objekteigenschaften
  • Example#3512 - Häufige Fehler bei der Verwendung von json_decode
  • Example#3513 - Fehler bei der Verwendung von depth
  • Example#3514 - json_decode von großen Ganzzahlen
  • Example#3515 - Ein json_encode-Beispiel
  • Example#3516 - Ein json_encode-Beispiel, das den Einsatz einiger Optionen zeigt
  • Example#3517 - JSON_NUMERIC_CHECK-Option-Beispiel
  • Example#3518 - Beispiel für sequentielle und nicht sequentielle Arrays
  • Example#3519 - JSON_PRESERVE_ZERO_FRACTION-Option-Beispiel
  • Example#3520 - json_last_error-Beispiel
  • Example#3521 - json_last_error mit json_encode
  • Example#3522 - json_last_error und JSON_THROW_ON_ERROR
  • Example#3523 - json_validate examples
  • Example#3524 - simdjson_decode examples
  • Example#3525 - Accessing invalid object properties
  • Example#3526 - common mistakes using simdjson_decode
  • Example#3527 - depth errors
  • Example#3528 - simdjson_decode of large integers
  • Example#3529 - simdjson_decode examples
  • Example#3530 - depth errors
  • Example#3531 - Lua::assignexample
  • Example#3532 - Lua::callexample
  • Example#3533 - Lua::evalexample
  • Example#3534 - Lua::registerCallbackexample
  • Example#3535 - LuaClosure::__invokeexample
  • Example#3536 - Execute some Lua code
  • Example#3537 - Calling a Lua function
  • Example#3538 - Profiling Lua code
  • Example#3539 - Loading code into Lua
  • Example#3540 - Manipulating the usage timer
  • Example#3541 - Registering PHP functions to call from Lua
  • Example#3542 - Calling a Lua function
  • Example#3543 - Calling a Lua function
  • Example#3544 - Verwendung von constant mit Konstanten
  • Example#3545 - Verwendung von constant mit Enum-Cases (seit PHP 8.1.0)
  • Example#3546 - Konstanten definieren
  • Example#3547 - Konstanten mit reservierten Namen
  • Example#3548 - Konstanten überprüfen
  • Example#3549 - Enum-Cases überprüfen (seit PHP 8.1.0)
  • Example#3550 - eval-Beispiel (einfache Texteinfügung)
  • Example#3551 - exit-Beispiel
  • Example#3552 - exit-Status-Beispiel
  • Example#3553 - Shutdown-Funktionen und Destruktoren werden trotzdem aufgerufen
  • Example#3554 - Auflistung aller Informationen über den Browser des Benutzers
  • Example#3555 - Ein __halt_compiler-Beispiel
  • Example#3556 - highlight_string-Beispiel
  • Example#3557 - hrtime usage
  • Example#3558 - Ein ignore_user_abort-Beispiel
  • Example#3559 - pack-Beispiel
  • Example#3560 - php_strip_whitespace example
  • Example#3561 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3562 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3563 - sapi_windows_vt100_support default state
  • Example#3564 - sapi_windows_vt100_support changing state
  • Example#3565 - Example usage of VT100 support enabled
  • Example#3566 - sleep-Beispiel
  • Example#3567 - sys_getloadavg-Beispiel
  • Example#3568 - time_nanosleep-Beispiel
  • Example#3569 - Ein time_sleep_until-Beispiel
  • Example#3570 - uniqid-Beispiel
  • Example#3571 - unpack-Beispiel
  • Example#3572 - unpack-Beispiel mit Wiederholer
  • Example#3573 - unpack-Beispiel mit unbenannten Schlüsseln
  • Example#3574 - usleep-Beispiel
  • Example#3575 - Random Example
  • Example#3576 - mt_rand-Beispiel
  • Example#3577 - rand-Beispiel
  • Example#3578 - random_bytes example
  • Example#3579 - random_int example
  • Example#3580 - Random\Randomizer::__construct example
  • Example#3581 - Random\Randomizer::getBytes example
  • Example#3582 - Random\Randomizer::getBytesFromString example
  • Example#3583 - Generate a random code for multi-factor authentication
  • Example#3584 - Select from a string with a non-uniform distribution
  • Example#3585 - Random\Randomizer::getFloat example
  • Example#3586 - Random\Randomizer::getInt example
  • Example#3587 - Random\Randomizer::nextFloat example
  • Example#3588 - Incorrect scaling using an affine transformation
  • Example#3589 - Random\Randomizer::nextInt example
  • Example#3590 - Random\Randomizer::pickArrayKeys example
  • Example#3591 - Picking random values
  • Example#3592 - Random\Randomizer::__serialize example
  • Example#3593 - Random\Randomizer::shuffleArray example
  • Example#3594 - Random\Randomizer::shuffleBytes example
  • Example#3595 - Byte-wise shuffling breaks Unicode characters
  • Example#3596 - Random\Randomizer::__unserialize example
  • Example#3597 - Random\Engine::generate example
  • Example#3598 - Random\Engine\Mt19937::__construct example
  • Example#3599 - Random\Engine\Mt19937::__debugInfo example
  • Example#3600 - Random\Engine\Mt19937::__serialize example
  • Example#3601 - Random\Engine\Mt19937::__unserialize example
  • Example#3602 - Random\Engine\PcgOneseq128XslRr64::__construct example
  • Example#3603 - Deriving a seed from a String
  • Example#3604 - Random\Engine\PcgOneseq128XslRr64::__debugInfo example
  • Example#3605 - Random\Engine\PcgOneseq128XslRr64::jump example
  • Example#3606 - Randomizer methods may call the engine more than once
  • Example#3607 - Random\Engine\PcgOneseq128XslRr64::__serialize example
  • Example#3608 - Random\Engine\PcgOneseq128XslRr64::__unserialize example
  • Example#3609 - Random\Engine\Xoshiro256StarStar::__construct example
  • Example#3610 - Deriving a seed from a String
  • Example#3611 - Random\Engine\Xoshiro256StarStar::__debugInfo example
  • Example#3612 - Random\Engine\Xoshiro256StarStar::jump example
  • Example#3613 - Random\Engine\Xoshiro256StarStar::jumpLong example
  • Example#3614 - Random\Engine\Xoshiro256StarStar::__serialize example
  • Example#3615 - Random\Engine\Xoshiro256StarStar::__unserialize example
  • Example#3616 - Get and set base path
  • Example#3617 - Get and set logger
  • Example#3618 - Fast write log
  • Example#3619 - Fast count some type of log count value
  • Example#3620 - Acquisit some type of log list
  • Example#3621 - seaslog_get_author example
  • Example#3622 - seaslog_get_version example
  • Example#3623 - SeasLog::alert example
  • Example#3624 - SeasLog::analyzerCount example
  • Example#3625 - SeasLog::analyzerDetail example
  • Example#3626 - SeasLog::closeLoggerStream example
  • Example#3627 - SeasLog::__construct example
  • Example#3628 - SeasLog::critical example
  • Example#3629 - SeasLog::debug example
  • Example#3630 - SeasLog::__destruct example
  • Example#3631 - SeasLog::emergency example
  • Example#3632 - SeasLog::error example
  • Example#3633 - SeasLog::flushBuffer example
  • Example#3634 - SeasLog::getBasePath example
  • Example#3635 - SeasLog::getBuffer example
  • Example#3636 - SeasLog::getBufferEnabled example
  • Example#3637 - SeasLog::getDatetimeFormat example
  • Example#3638 - SeasLog::getLastLogger example
  • Example#3639 - SeasLog::getRequestID example
  • Example#3640 - SeasLog::getRequestVariable example
  • Example#3641 - SeasLog::info example
  • Example#3642 - SeasLog::log example
  • Example#3643 - SeasLog::notice example
  • Example#3644 - SeasLog::setBasePath example
  • Example#3645 - SeasLog::setDatetimeFormat example
  • Example#3646 - SeasLog::setLogger example
  • Example#3647 - SeasLog::setRequestID example
  • Example#3648 - SeasLog::setRequestVariable example
  • Example#3649 - SeasLog::warning example
  • Example#3650 - SplStack example
  • Example#3651 - SplQueue example
  • Example#3652 - Efficiently handling tasks with SplQueue
  • Example#3653 - SplFixedArray usage example
  • Example#3654 - SplFixedArray::__construct example
  • Example#3655 - SplFixedArray::count example
  • Example#3656 - SplFixedArray::fromArray example
  • Example#3657 - SplFixedArray::getSize example
  • Example#3658 - SplFixedArray::setSize example
  • Example#3659 - SplFixedArray::toArray example
  • Example#3660 - SplObjectStorage as a set
  • Example#3661 - SplObjectStorage as a map
  • Example#3662 - SplObjectStorage::addAll example
  • Example#3663 - SplObjectStorage::attach example
  • Example#3664 - SplObjectStorage::contains example
  • Example#3665 - SplObjectStorage::count example
  • Example#3666 - SplObjectStorage::current example
  • Example#3667 - SplObjectStorage::detach example
  • Example#3668 - SplObjectStorage::getHash example
  • Example#3669 - SplObjectStorage::getInfo example
  • Example#3670 - SplObjectStorage::key example
  • Example#3671 - SplObjectStorage::next example
  • Example#3672 - SplObjectStorage::offsetExists example
  • Example#3673 - SplObjectStorage::offsetGet example
  • Example#3674 - SplObjectStorage::offsetSet example
  • Example#3675 - SplObjectStorage::offsetUnset example
  • Example#3676 - SplObjectStorage::removeAll example
  • Example#3677 - SplObjectStorage::removeAllExcept example
  • Example#3678 - SplObjectStorage::rewind example
  • Example#3679 - SplObjectStorage::serialize example
  • Example#3680 - SplObjectStorage::setInfo example
  • Example#3681 - SplObjectStorage::unserialize example
  • Example#3682 - SplObjectStorage::valid example
  • Example#3683 - AppendIterator::append example
  • Example#3684 - Iterating AppendIterator with foreach
  • Example#3685 - Iterating AppendIterator with the AppendIterator API
  • Example#3686 - AppendIterator.getIteratorIndex basic example
  • Example#3687 - AppendIterator::key basic example
  • Example#3688 - ArrayIterator::current example
  • Example#3689 - ArrayIterator::key example
  • Example#3690 - ArrayIterator::next example
  • Example#3691 - ArrayIterator::rewind example
  • Example#3692 - ArrayIterator::valid example
  • Example#3693 - CachingIterator::getCache example
  • Example#3694 - Available callback arguments
  • Example#3695 - Callback basic examples
  • Example#3696 - A DirectoryIterator::__construct example
  • Example#3697 - A DirectoryIterator::current example
  • Example#3698 - A DirectoryIterator::getBasename example
  • Example#3699 - DirectoryIterator::getExtension example
  • Example#3700 - A DirectoryIterator::getFilename example
  • Example#3701 - A DirectoryIterator::isDot example
  • Example#3702 - A DirectoryIterator::key example
  • Example#3703 - DirectoryIterator::next example
  • Example#3704 - DirectoryIterator::rewind example
  • Example#3705 - DirectoryIterator::seek example
  • Example#3706 - A DirectoryIterator::__toString example
  • Example#3707 - A DirectoryIterator::valid example
  • Example#3708 - FilesystemIterator::__construct example
  • Example#3709 - FilesystemIterator::current example
  • Example#3710 - FilesystemIterator::key example
  • Example#3711 - FilesystemIterator::next example
  • Example#3712 - FilesystemIterator::rewind example
  • Example#3713 - FilesystemIterator::key example
  • Example#3714 - FilterIterator::accept example
  • Example#3715 - GlobIterator example
  • Example#3716 - GlobIterator::count example
  • Example#3717 - InfiniteIterator::__construct example
  • Example#3718 - LimitIterator usage example
  • Example#3719 - LimitIterator::__construct example
  • Example#3720 - LimitIterator::getPosition example
  • Example#3721 - Iterating a MultipleIterator
  • Example#3722 - NoRewindIterator::__construct example
  • Example#3723 - NoRewindIterator::rewind example
  • Example#3724 - RecursiveArrayIterator::getChildren example
  • Example#3725 - RecursiveArrayIterator::hasChildren example
  • Example#3726 - Available callback arguments
  • Example#3727 - Recursive callback basic example
  • Example#3728 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#3729 - RecursiveDirectoryIterator example
  • Example#3730 - getSubPath example
  • Example#3731 - getSubPathname example
  • Example#3732 - Basic RecursiveFilterIterator example
  • Example#3733 - RecursiveFilterIterator example
  • Example#3734 - Iterating a RecursiveIteratorIterator
  • Example#3735 - RecursiveRegexIterator::__construct example
  • Example#3736 - RecursiveRegexIterator::getChildren example
  • Example#3737 - RecursiveRegexIterator::hasChildren example
  • Example#3738 - RegexIterator::accept example
  • Example#3739 - RegexIterator::__construct example
  • Example#3740 - RegexIterator::getFlags example
  • Example#3741 - RegexIterator::getMode example
  • Example#3742 - RegexIterator::getPregFlags example
  • Example#3743 - RegexIterator::setFlags example
  • Example#3744 - RegexIterator::setMode example
  • Example#3745 - RegexIterator::setPregFlags example
  • Example#3746 - Countable::count-Beispiel
  • Example#3747 - Basic usage
  • Example#3748 - SeekableIterator::seek example
  • Example#3749 - class_implements example
  • Example#3750 - class_parents example
  • Example#3751 - class_uses example
  • Example#3752 - iterator_apply example
  • Example#3753 - iterator_count example
  • Example#3754 - iterator_count modifies position
  • Example#3755 - iterator_count in foreach loops
  • Example#3756 - iterator_to_array example
  • Example#3757 - spl_autoload_extensions Beispiel
  • Example#3758 - spl_autoload_register as a replacement for an __autoload function
  • Example#3759 - spl_autoload_register example where the class is not loaded
  • Example#3760 - The identifier will be provided without the leading backslash
  • Example#3761 - spl_classes example
  • Example#3762 - A spl_object_hash example
  • Example#3763 - A spl_object_id example
  • Example#3764 - SplFileInfo::__construct example
  • Example#3765 - SplFileInfo::getATime example
  • Example#3766 - SplFileInfo::getBasename example
  • Example#3767 - SplFileInfo::getCTime example
  • Example#3768 - SplFileInfo::getExtension example
  • Example#3769 - SplFileInfo::getFilename example
  • Example#3770 - SplFileInfo::getGroup example
  • Example#3771 - SplFileInfo::getLinkTarget example
  • Example#3772 - SplFileInfo::getMTime example
  • Example#3773 - SplFileInfo::getOwner example
  • Example#3774 - SplFileInfo::getPath example
  • Example#3775 - SplFileInfo::getPathInfo example
  • Example#3776 - SplFileInfo::getPathname example
  • Example#3777 - SplFileInfo::getPerms example
  • Example#3778 - SplFileInfo::getRealPath example
  • Example#3779 - SplFileInfo::getSize example
  • Example#3780 - SplFileInfo::getType example
  • Example#3781 - SplFileInfo::isDir example
  • Example#3782 - SplFileInfo::isExecutable example
  • Example#3783 - SplFileInfo::isFile example
  • Example#3784 - SplFileInfo::isLink example
  • Example#3785 - SplFileInfo::isReadable example
  • Example#3786 - SplFileInfo::isWriteable example
  • Example#3787 - SplFileInfo::openFile example
  • Example#3788 - SplFileInfo::setFileClass example
  • Example#3789 - SplFileInfo::setFileClass example
  • Example#3790 - SplFileInfo::__toString example
  • Example#3791 - SplFileObject::__construct example
  • Example#3792 - SplFileObject::current example
  • Example#3793 - SplFileObject::eof example
  • Example#3794 - SplFileObject::fflush example
  • Example#3795 - SplFileObject::fgetc example
  • Example#3796 - SplFileObject::fgetcsv example
  • Example#3797 - SplFileObject::READ_CSV example
  • Example#3798 - SplFileObject::fgets example
  • Example#3799 - SplFileObject::fgetss example
  • Example#3800 - SplFileObject::flock example
  • Example#3801 - SplFileObject::fpassthru example
  • Example#3802 - SplFileObject::fputcsv example
  • Example#3803 - SplFileObject::fread example
  • Example#3804 - SplFileObject::fscanf example
  • Example#3805 - SplFileObject::fseek example
  • Example#3806 - SplFileObject::fstat example
  • Example#3807 - SplFileObject::ftell example
  • Example#3808 - SplFileObject::ftruncate example
  • Example#3809 - SplFileObject::fwrite example
  • Example#3810 - SplFileObject::getCsvControl example
  • Example#3811 - SplFileObject::getFlags example
  • Example#3812 - SplFileObject::getMaxLineLen example
  • Example#3813 - SplFileObject::key example
  • Example#3814 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#3815 - SplFileObject::next example
  • Example#3816 - SplFileObject::rewind example
  • Example#3817 - SplFileObject::seek example
  • Example#3818 - SplFileObject::setCsvControl example
  • Example#3819 - SplFileObject::setFlags example
  • Example#3820 - SplFileObject::setMaxLineLen example
  • Example#3821 - SplFileObject::valid example
  • Example#3822 - SplTempFileObject example
  • Example#3823 - ArrayObject::append example
  • Example#3824 - ArrayObject::asort example
  • Example#3825 - ArrayObject::__construct example
  • Example#3826 - ArrayObject::count example
  • Example#3827 - ArrayObject::exchangeArray example
  • Example#3828 - ArrayObject::getArrayCopy example
  • Example#3829 - ArrayObject::getFlags example
  • Example#3830 - ArrayObject::getIterator example
  • Example#3831 - ArrayObject::getIteratorClass example
  • Example#3832 - ArrayObject::ksort example
  • Example#3833 - ArrayObject::natcasesort example
  • Example#3834 - ArrayObject::natsort example
  • Example#3835 - ArrayObject::offsetExists example
  • Example#3836 - ArrayObject::offsetGet example
  • Example#3837 - ArrayObject::offsetSet example
  • Example#3838 - ArrayObject::offsetUnset example
  • Example#3839 - ArrayObject::serialize example
  • Example#3840 - ArrayObject::setFlags example
  • Example#3841 - ArrayObject::setIteratorClass example
  • Example#3842 - ArrayObject::uasort example
  • Example#3843 - ArrayObject::uksort example
  • Example#3844 - Using file_get_contents to retrieve data from multiple sources
  • Example#3845 - Making a POST request to an https server
  • Example#3846 - Writing data to a compressed file
  • Example#3847 - A Stream for reading/writing global variables
  • Example#3848 - Listing files from tar archives
  • Example#3849 - stream_bucket_prepend examples
  • Example#3850 - Using stream_context_create
  • Example#3851 - Using stream_context_get_default
  • Example#3852 - stream_context_get_options example
  • Example#3853 - stream_context_get_params example
  • Example#3854 - stream_context_set_default example
  • Example#3855 - stream_context_set_options example
  • Example#3856 - A stream_copy_to_stream example
  • Example#3857 - Controlling where filters are applied
  • Example#3858 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#3859 - Registering a generic filter class to match multiple filter names.
  • Example#3860 - Dynamically refiltering a stream
  • Example#3861 - stream_get_contents example
  • Example#3862 - Using stream_get_filters
  • Example#3863 - stream_get_meta_data example using fopen with http
  • Example#3864 - stream_get_meta_data example using stream_socket_client with https
  • Example#3865 - Using stream_get_transports
  • Example#3866 - stream_get_wrappers example
  • Example#3867 - Checking for the existence of a stream wrapper
  • Example#3868 - stream_is_local example
  • Example#3869 - stream_isatty example
  • Example#3870 - stream_notification_callback example
  • Example#3871 - Simple progressbar for commandline download client
  • Example#3872 - stream_resolve_include_path example
  • Example#3873 - stream_select Example
  • Example#3874 - stream_set_timeout example
  • Example#3875 - stream_set_write_buffer example
  • Example#3876 - stream_socket_client example
  • Example#3877 - Using UDP connection
  • Example#3878 - stream_socket_enable_crypto example
  • Example#3879 - A stream_socket_pair example
  • Example#3880 - stream_socket_recvfrom example
  • Example#3881 - stream_socket_sendto Example
  • Example#3882 - Using TCP server sockets
  • Example#3883 - Using UDP server sockets
  • Example#3884 - A stream_socket_shutdown example
  • Example#3885 - How to register a stream wrapper
  • Example#3886 - Basic Tidy usage
  • Example#3887 - tidy::getBody example
  • Example#3888 - tidy::cleanrepair example
  • Example#3889 - tidy::__construct example
  • Example#3890 - tidy::diagnose example
  • Example#3891 - tidy_get_error_buffer example
  • Example#3892 - tidy::getConfig example
  • Example#3893 - tidy_getopt example
  • Example#3894 - Print all options along with their documentation and default value
  • Example#3895 - tidy::getStatus example
  • Example#3896 - tidy::head example
  • Example#3897 - tidy::html example
  • Example#3898 - tidy::parseFile example
  • Example#3899 - tidy::parseString example
  • Example#3900 - tidy::repairFile example
  • Example#3901 - tidy::repairString example
  • Example#3902 - tidy::root example
  • Example#3903 - tidyNode::hasChildren example
  • Example#3904 - tidyNode::hasChildren example
  • Example#3905 - tidyNode::hasSiblings example
  • Example#3906 - Extract ASP code from a mixed HTML document
  • Example#3907 - Extract comments from a mixed HTML document
  • Example#3908 - Extract HTML code from a mixed HTML document
  • Example#3909 - Extract JSTE code from a mixed HTML document
  • Example#3910 - Extract PHP code from a mixed HTML document
  • Example#3911 - Extract text from a mixed HTML document
  • Example#3912 - ob_tidyhandler example
  • Example#3913 - tidy_access_count example
  • Example#3914 - tidy_config_count example
  • Example#3915 - tidy_error_count example
  • Example#3916 - tidy_get_output example
  • Example#3917 - tidy_warning_count example
  • Example#3918 - Kommentare mit Hilfe des Tokenizers entfernen
  • Example#3919 - PhpToken::getTokenName example
  • Example#3920 - PhpToken::is example
  • Example#3921 - Usage with array
  • Example#3922 - PhpToken::isIgnorable example
  • Example#3923 - PhpToken::__toString example
  • Example#3924 - PhpToken::tokenize example
  • Example#3925 - Extending PhpToken
  • Example#3926 - token_get_all-Beispiel
  • Example#3927 - Fehlerhaftes token_get_all-Verwendungsbeispiel
  • Example#3928 - token_get_all für eine Klasse, die ein reserviertes Wort benutzt
  • Example#3929 - token_name-Beispiele
  • Example#3930 - base64_decode-Beispiel
  • Example#3931 - base64_encode-Beispiel
  • Example#3932 - get_headers-Beispiel
  • Example#3933 - get_headers-Beispiel unter Verwendung von HEAD
  • Example#3934 - Was get_meta_tags parst
  • Example#3935 - Was get_meta_tags zurückgibt
  • Example#3936 - Einfache Verwendung von http_build_query
  • Example#3937 - http_build_query mit numerischen Index-Elementen.
  • Example#3938 - http_build_query mit verschachtelten Arrays
  • Example#3939 - Verwendung von http_build_query mit einem Objekt
  • Example#3940 - Ein parse_url-Beispiel
  • Example#3941 - Ein parse_url-Beispiel mit fehlendem Schema
  • Example#3942 - rawurldecode-Beispiel
  • Example#3943 - Übergeben eines Passworts in einer FTP-URL
  • Example#3944 - rawurlencode-Beispiel 2
  • Example#3945 - urldecode-Beispiel
  • Example#3946 - urlencode-Beispiel
  • Example#3947 - urlencode und htmlentities-Beispiel
  • Example#3948 - Einfache Ausführung von JavaScript
  • Example#3949 - Yaml Example
  • Example#3950 - Parse callback example
  • Example#3951 - Emit callback example
  • Example#3952 - yaml_emit example
  • Example#3953 - yaml_parse example
  • Example#3954 - A classic Application directory layout
  • Example#3955 - Entry
  • Example#3956 - Rewrite rule
  • Example#3957 - Application config
  • Example#3958 - Default controller
  • Example#3959 - Default view template
  • Example#3960 - Run the Application
  • Example#3961 - An PHP array example
  • Example#3962 - An ini file example
  • Example#3963 - A Bootstrapexample
  • Example#3964 - Yaf_Application::bootstrapexample
  • Example#3965 - Yaf_Application::clearLastErrorexample
  • Example#3966 - A ini config file example
  • Example#3967 - Yaf_Application::__constructexample
  • Example#3968 - Yaf_Application::__constructexample
  • Example#3969 - Yaf_Application::environexample
  • Example#3970 - Yaf_Application::executeexample
  • Example#3971 - Yaf_Application::getConfigexample
  • Example#3972 - Yaf_Application::getDispatcherexample
  • Example#3973 - Yaf_Application::getLastErrorMsgexample
  • Example#3974 - Yaf_Application::getLastErrorNoexample
  • Example#3975 - Yaf_Application::getModulesexample
  • Example#3976 - Bootstrap example
  • Example#3977 - Yaf_Dispatcher::autoRender example
  • Example#3978 - Yaf_Dispatcher::catchException example
  • Example#3979 - Yaf_Dispatcher::registerPlugin example
  • Example#3980 - A custom View engine example
  • Example#3981 - Yaf_Dispatcher::setView example
  • Example#3982 - Yaf_Dispatcher::throwexception example
  • Example#3983 - Yaf_Dispatcher::throwexceptionexample
  • Example#3984 - Yaf_Config_Iniexample
  • Example#3985 - define action in a separate file
  • Example#3986 - Dummy_action.php
  • Example#3987 - Yaf_Controller_Abstract::forwardexample
  • Example#3988 - Yaf_Action_Abstract::executeexample
  • Example#3989 - Yaf_Action_Abstract::executeexample
  • Example#3990 - Yaf_View_Simple::assignexample
  • Example#3991 - templateexample
  • Example#3992 - Yaf_View_Simple::assignRefexample
  • Example#3993 - templateexample
  • Example#3994 - Yaf_View_Simple::clearexample
  • Example#3995 - Yaf_View_Simple::__constructorexample
  • Example#3996 - Yaf_View_Simple::__setexample
  • Example#3997 - Config example
  • Example#3998 - Register localnamespace
  • Example#3999 - Load class example
  • Example#4000 - Load namespace class example
  • Example#4001 - MVC class loading example
  • Example#4002 - MVC class distinctions
  • Example#4003 - MVC loading example
  • Example#4004 - Yaf_Loader::registerNamespaceexample
  • Example#4005 - Yaf_Loader::registerLocalNamespaceexample
  • Example#4006 - Yaf_Loader::registerNamespaceexample
  • Example#4007 - Plugin example
  • Example#4008 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#4009 - Yaf_Response_Abstract::appendBodyexample
  • Example#4010 - Yaf_Response_Abstract::getBodyexample
  • Example#4011 - Yaf_Response_Abstract::prependBodyexample
  • Example#4012 - Yaf_Response_Abstract::responseexample
  • Example#4013 - Yaf_Response_Abstract::setBodyexample
  • Example#4014 - Yaf_Route_Map::assembleexample
  • Example#4015 - Yaf_Route_Mapexample
  • Example#4016 - Yaf_Route_Mapexample
  • Example#4017 - Yaf_Route_Mapexample
  • Example#4018 - Yaf_Route_Regex::assembleexample
  • Example#4019 - Yaf_Route_Regexexample
  • Example#4020 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#4021 - Yaf_Route_Regex and named capture ground(as of 2.3.0)example
  • Example#4022 - Yaf_Route_Regexexample
  • Example#4023 - Yaf_Route_Rewrite::assembleexample
  • Example#4024 - Yaf_Route_Rewriteexample
  • Example#4025 - Yaf_Route_Rewriteexample
  • Example#4026 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#4027 - Rewrite rule for Apache
  • Example#4028 - Rewrite rule for Apache
  • Example#4029 - Rewrite rule for Lighttpd
  • Example#4030 - Rewrite rule for Nginx
  • Example#4031 - Yaf_Route_Static(default route)example
  • Example#4032 - application.iniexample
  • Example#4033 - Yaf_Dispatcher::autoConfigexample
  • Example#4034 - Yaf_Dispatcher::autoRenderexample
  • Example#4035 - Register some routes in Bootstrap
  • Example#4036 - plugin Dummy.php (under application.directory/plugins)
  • Example#4037 - Yaf_Route_Simple::assembleexample
  • Example#4038 - Yaf_Route_Simple::routeexample
  • Example#4039 - Yaf_Route_Simple::routeexample
  • Example#4040 - Yaf_Route_Static::assembleexample
  • Example#4041 - Yaf_Route_Static::routeexample
  • Example#4042 - Yaf_Route_Supervar::assemble example
  • Example#4043 - Yaf_Route_Supervarexample
  • Example#4044 - INI example
  • Example#4045 - INI sections example
  • Example#4046 - INIexample
  • Example#4047 - Taintexample
  • Example#4048 - Vector
  • Example#4049 - Map
  • Example#4050 - Ds\Collection::clear example
  • Example#4051 - Ds\Collection::copy example
  • Example#4052 - Ds\Collection::isEmpty example
  • Example#4053 - Ds\Collection::toArray example
  • Example#4054 - Ds\Hashable::hash example
  • Example#4055 - Ds\Sequence::allocate example
  • Example#4056 - Ds\Sequence::apply example
  • Example#4057 - Ds\Sequence::capacity example
  • Example#4058 - Ds\Sequence::contains example
  • Example#4059 - Ds\Sequence::filter example using callback function
  • Example#4060 - Ds\Sequence::filter example without a callback function
  • Example#4061 - Ds\Sequence::find example
  • Example#4062 - Ds\Sequence::first example
  • Example#4063 - Ds\Sequence::get example
  • Example#4064 - Ds\Sequence::get example using array syntax
  • Example#4065 - Ds\Sequence::insert example
  • Example#4066 - Ds\Sequence::join example using a separator string
  • Example#4067 - Ds\Sequence::join example without a separator string
  • Example#4068 - Ds\Sequence::last example
  • Example#4069 - Ds\Sequence::map example
  • Example#4070 - Ds\Sequence::merge example
  • Example#4071 - Ds\Sequence::pop example
  • Example#4072 - Ds\Sequence::push example
  • Example#4073 - Ds\Sequence::reduce with initial value example
  • Example#4074 - Ds\Sequence::reduce without an initial value example
  • Example#4075 - Ds\Sequence::remove example
  • Example#4076 - Ds\Sequence::reverse example
  • Example#4077 - Ds\Sequence::reversed example
  • Example#4078 - Ds\Sequence::rotate example
  • Example#4079 - Ds\Sequence::set example
  • Example#4080 - Ds\Sequence::set example using array syntax
  • Example#4081 - Ds\Sequence::shift example
  • Example#4082 - Ds\Sequence::slice example
  • Example#4083 - Ds\Sequence::sort example
  • Example#4084 - Ds\Sequence::sort example using a comparator
  • Example#4085 - Ds\Sequence::sorted example
  • Example#4086 - Ds\Sequence::sorted example using a comparator
  • Example#4087 - Ds\Sequence::sum integer example
  • Example#4088 - Ds\Sequence::sum float example
  • Example#4089 - Ds\Sequence::unshift example
  • Example#4090 - Ds\Vector::allocate example
  • Example#4091 - Ds\Vector::apply example
  • Example#4092 - Ds\Vector::capacity example
  • Example#4093 - Ds\Vector::clear example
  • Example#4094 - Ds\Vector::__construct example
  • Example#4095 - Ds\Vector::contains example
  • Example#4096 - Ds\Vector::copy example
  • Example#4097 - Ds\Vector::filter example using callback function
  • Example#4098 - Ds\Vector::filter example without a callback function
  • Example#4099 - Ds\Vector::find example
  • Example#4100 - Ds\Vector::first example
  • Example#4101 - Ds\Vector::get example
  • Example#4102 - Ds\Vector::get example using array syntax
  • Example#4103 - Ds\Vector::insert example
  • Example#4104 - Ds\Vector::isEmpty example
  • Example#4105 - Ds\Vector::join example using a separator string
  • Example#4106 - Ds\Vector::join example without a separator string
  • Example#4107 - Ds\Vector::last example
  • Example#4108 - Ds\Vector::map example
  • Example#4109 - Ds\Vector::merge example
  • Example#4110 - Ds\Vector::pop example
  • Example#4111 - Ds\Vector::push example
  • Example#4112 - Ds\Vector::reduce with initial value example
  • Example#4113 - Ds\Vector::reduce without an initial value example
  • Example#4114 - Ds\Vector::remove example
  • Example#4115 - Ds\Vector::reverse example
  • Example#4116 - Ds\Vector::reversed example
  • Example#4117 - Ds\Vector::rotate example
  • Example#4118 - Ds\Vector::set example
  • Example#4119 - Ds\Vector::set example using array syntax
  • Example#4120 - Ds\Vector::shift example
  • Example#4121 - Ds\Vector::slice example
  • Example#4122 - Ds\Vector::sort example
  • Example#4123 - Ds\Vector::sort example using a comparator
  • Example#4124 - Ds\Vector::sorted example
  • Example#4125 - Ds\Vector::sorted example using a comparator
  • Example#4126 - Ds\Vector::sum integer example
  • Example#4127 - Ds\Vector::sum float example
  • Example#4128 - Ds\Vector::toArray example
  • Example#4129 - Ds\Vector::unshift example
  • Example#4130 - Ds\Deque::allocate example
  • Example#4131 - Ds\Deque::apply example
  • Example#4132 - Ds\Deque::capacity example
  • Example#4133 - Ds\Deque::clear example
  • Example#4134 - Ds\Deque::__construct example
  • Example#4135 - Ds\Deque::contains example
  • Example#4136 - Ds\Deque::copy example
  • Example#4137 - Ds\Deque::filter example using callback function
  • Example#4138 - Ds\Deque::filter example without a callback function
  • Example#4139 - Ds\Deque::find example
  • Example#4140 - Ds\Deque::first example
  • Example#4141 - Ds\Deque::get example
  • Example#4142 - Ds\Deque::get example using array syntax
  • Example#4143 - Ds\Deque::insert example
  • Example#4144 - Ds\Deque::isEmpty example
  • Example#4145 - Ds\Deque::join example using a separator string
  • Example#4146 - Ds\Deque::join example without a separator string
  • Example#4147 - Ds\Deque::last example
  • Example#4148 - Ds\Deque::map example
  • Example#4149 - Ds\Deque::merge example
  • Example#4150 - Ds\Deque::pop example
  • Example#4151 - Ds\Deque::push example
  • Example#4152 - Ds\Deque::reduce with initial value example
  • Example#4153 - Ds\Deque::reduce without an initial value example
  • Example#4154 - Ds\Deque::remove example
  • Example#4155 - Ds\Deque::reverse example
  • Example#4156 - Ds\Deque::reversed example
  • Example#4157 - Ds\Deque::rotate example
  • Example#4158 - Ds\Deque::set example
  • Example#4159 - Ds\Deque::set example using array syntax
  • Example#4160 - Ds\Deque::shift example
  • Example#4161 - Ds\Deque::slice example
  • Example#4162 - Ds\Deque::sort example
  • Example#4163 - Ds\Deque::sort example using a comparator
  • Example#4164 - Ds\Deque::sorted example
  • Example#4165 - Ds\Deque::sorted example using a comparator
  • Example#4166 - Ds\Deque::sum integer example
  • Example#4167 - Ds\Deque::sum float example
  • Example#4168 - Ds\Deque::toArray example
  • Example#4169 - Ds\Deque::unshift example
  • Example#4170 - Ds\Map::allocate example
  • Example#4171 - Ds\Map::apply example
  • Example#4172 - Ds\Map::capacity example
  • Example#4173 - Ds\Map::clear example
  • Example#4174 - Ds\Map::__construct example
  • Example#4175 - Ds\Map::copy example
  • Example#4176 - Ds\Map::diff example
  • Example#4177 - Ds\Map::filter example using callback function
  • Example#4178 - Ds\Map::filter example without a callback function
  • Example#4179 - Ds\Map::first example
  • Example#4180 - Ds\Map::get example
  • Example#4181 - Ds\Map::get example using array syntax
  • Example#4182 - Ds\Map::hasKey example
  • Example#4183 - Ds\Map::hasValue example
  • Example#4184 - Ds\Map::intersect example
  • Example#4185 - Ds\Map::isEmpty example
  • Example#4186 - Ds\Map::keys example
  • Example#4187 - Ds\Map::ksort example
  • Example#4188 - Ds\Map::ksort example using a comparator
  • Example#4189 - Ds\Map::ksorted example
  • Example#4190 - Ds\Map::ksorted example using a comparator
  • Example#4191 - Ds\Map::last example
  • Example#4192 - Ds\Map::map example
  • Example#4193 - Ds\Map::merge example
  • Example#4194 - Ds\Map::pairs example
  • Example#4195 - Ds\Map::put example
  • Example#4196 - Ds\Map::put example using objects as keys
  • Example#4197 - Ds\Map::putAll example
  • Example#4198 - Ds\Map::reduce with initial value example
  • Example#4199 - Ds\Map::reduce without an initial value example
  • Example#4200 - Ds\Map::remove example
  • Example#4201 - Ds\Map::reverse example
  • Example#4202 - Ds\Map::reversed example
  • Example#4203 - Ds\Map::skip example
  • Example#4204 - Ds\Map::slice example
  • Example#4205 - Ds\Map::sort example
  • Example#4206 - Ds\Map::sort example using a comparator
  • Example#4207 - Ds\Map::sort example
  • Example#4208 - Ds\Map::sort example using a comparator
  • Example#4209 - Ds\Map::sum integer example
  • Example#4210 - Ds\Map::sum float example
  • Example#4211 - Ds\Map::toArray example
  • Example#4212 - Ds\Map::union example
  • Example#4213 - Ds\Map::values example
  • Example#4214 - Ds\Map::xor example
  • Example#4215 - Ds\Pair::clear example
  • Example#4216 - Ds\Pair::copy example
  • Example#4217 - Ds\Pair::isEmpty example
  • Example#4218 - Ds\Pair::toArray example
  • Example#4219 - Ds\Set::add example using integers
  • Example#4220 - Ds\Set::add example using objects
  • Example#4221 - Ds\Set::allocate example
  • Example#4222 - Ds\Set::capacity example
  • Example#4223 - Ds\Set::clear example
  • Example#4224 - Ds\Set::__construct example
  • Example#4225 - Ds\Set::contains example
  • Example#4226 - Ds\Set::copy example
  • Example#4227 - Ds\Set::diff example
  • Example#4228 - Ds\Set::filter example using callback function
  • Example#4229 - Ds\Set::filter example without a callback function
  • Example#4230 - Ds\Set::first example
  • Example#4231 - Ds\Set::get example
  • Example#4232 - Ds\Set::get example using array syntax
  • Example#4233 - Ds\Set::intersect example
  • Example#4234 - Ds\Set::isEmpty example
  • Example#4235 - Ds\Set::join example using a separator string
  • Example#4236 - Ds\Set::join example without a separator string
  • Example#4237 - Ds\Set::last example
  • Example#4238 - Ds\Set::merge example
  • Example#4239 - Ds\Set::reduce with initial value example
  • Example#4240 - Ds\Set::reduce without an initial value example
  • Example#4241 - Ds\Set::remove example
  • Example#4242 - Ds\Set::reverse example
  • Example#4243 - Ds\Set::reversed example
  • Example#4244 - Ds\Set::slice example
  • Example#4245 - Ds\Set::sort example
  • Example#4246 - Ds\Set::sort example using a comparator
  • Example#4247 - Ds\Set::sorted example
  • Example#4248 - Ds\Set::sorted example using a comparator
  • Example#4249 - Ds\Set::sum integer example
  • Example#4250 - Ds\Set::sum float example
  • Example#4251 - Ds\Set::toArray example
  • Example#4252 - Ds\Set::union example
  • Example#4253 - Ds\Set::xor example
  • Example#4254 - Ds\Stack::clear example
  • Example#4255 - Ds\Stack::__construct example
  • Example#4256 - Ds\Stack::copy example
  • Example#4257 - Ds\Stack::isEmpty example
  • Example#4258 - Ds\Stack::peek example
  • Example#4259 - Ds\Stack::pop example
  • Example#4260 - Ds\Stack::push example
  • Example#4261 - Ds\Stack::toArray example
  • Example#4262 - Ds\Queue::allocate example
  • Example#4263 - Ds\Queue::capacity example
  • Example#4264 - Ds\Queue::clear example
  • Example#4265 - Ds\Queue::__construct example
  • Example#4266 - Ds\Queue::copy example
  • Example#4267 - Ds\Queue::isEmpty example
  • Example#4268 - Ds\Queue::peek example
  • Example#4269 - Ds\Queue::pop example
  • Example#4270 - Ds\Queue::push example
  • Example#4271 - Ds\Queue::toArray example
  • Example#4272 - Ds\PriorityQueue::allocate example
  • Example#4273 - Ds\PriorityQueue::capacity example
  • Example#4274 - Ds\PriorityQueue::clear example
  • Example#4275 - Ds\PriorityQueue::__construct example
  • Example#4276 - Ds\PriorityQueue::copy example
  • Example#4277 - Ds\PriorityQueue::isEmpty example
  • Example#4278 - Ds\PriorityQueue::peek example
  • Example#4279 - Ds\PriorityQueue::pop example
  • Example#4280 - Ds\PriorityQueue::push example
  • Example#4281 - Ds\PriorityQueue::toArray example
  • Example#4282 - var_representation Examples
  • Example#4283 - Escaping control characters
  • Example#4284 - Exporting stdClass
  • Example#4285 - Exporting classes
  • Example#4286 - Using __set_state()
  • Example#4287 - Nutzung von PHPs cURL-Modul, um die Homepage von example.com herunterzuladen
  • Example#4288 - Initialisierung einer neuen cURL-Session und Abrufen einer Webseite
  • Example#4289 - cURL-Handle kopieren
  • Example#4290 - curl_errno-Beispiel
  • Example#4291 - curl_error-Beispiel
  • Example#4292 - curl_escape-Beispiel
  • Example#4293 - Abrufen einer Webseite
  • Example#4294 - curl_getinfo-Beispiel
  • Example#4295 - curl_getinfo-Beispiel mit dem Parameter option
  • Example#4296 - Initialisieren einer neuen cURL-Session und abrufen einer Webseite
  • Example#4297 - curl_multi_add_handle-Beispiel
  • Example#4298 - curl_multi_close-Beispiel
  • Example#4299 - curl_multi_exec-Beispiel
  • Example#4300 - Ein curl_multi_info_read-Beispiel
  • Example#4301 - curl_multi_init-Beispiel
  • Example#4302 - curl_multi_strerror-Beispiel
  • Example#4303 - curl_reset-Beispiel
  • Example#4304 - Initialisierung einer cURL-Session und holen einer Webseite
  • Example#4305 - Initialisierung einer neuen cURL-Session und das Abrufen einer Webseite
  • Example#4306 - curl_share_setopt-Beispiel
  • Example#4307 - curl_share_init-Beispiel
  • Example#4308 - curl_share_setopt-Beispiel
  • Example#4309 - curl_errno-Beispiel
  • Example#4310 - curl_escape-Beispiel
  • Example#4311 - curl_upkeep-Beispiel
  • Example#4312 - Beispiel für curl_version
  • Example#4313 - CURLFile::__construct-Beispiel
  • Example#4314 - CURLFile::__construct-Beispiel zum Upload mehrerer Dateien
  • Example#4315 - CURLStringFile::__construct-Beispiel
  • Example#4316 - Simple HTTP client
  • Example#4317 - HTTP client using asynchronous DNS resolver
  • Example#4318 - Echo server
  • Example#4319 - SSL echo server
  • Example#4320 - Signal handler
  • Example#4321 - Use libevent's loop to process requests of `eio' extension
  • Example#4322 - Miscellaneous
  • Example#4323 - Simple HTTP server
  • Example#4324 - Simple HTTPS server
  • Example#4325 - OpenSSL connection
  • Example#4326 - EventHttpConnection::makeRequest example
  • Example#4327 - Connection listener based on a UNIX domain socket
  • Example#4328 - Simple SMTP server
  • Example#4329 - Handling SIGTERM signal
  • Example#4330 - Adding a custom signal
  • Example#4331 - Adding a timer
  • Example#4332 - EventBase::getFeatures example
  • Example#4333 - EventBase::getMethod example
  • Example#4334 - EventBuffer::search example
  • Example#4335 - EventBufferEvent::connect example
  • Example#4336 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4337 - EventBufferEvent::connectHost example
  • Example#4338 - Buffer event's read callback
  • Example#4339 - EventBufferEvent::getOutput example
  • Example#4340 - EventBufferEvent::sslError example
  • Example#4341 - Simple SMTP server
  • Example#4342 - EventConfig::avoidMethod example
  • Example#4343 - EventConfig::__construct example
  • Example#4344 - EventConfig::requireFeatures example
  • Example#4345 - EventHttp::accept example
  • Example#4346 - EventHttp::addServerAlias example
  • Example#4347 - EventHttp::bind example
  • Example#4348 - Simple HTTP server
  • Example#4349 - EventHttp::setCallback example
  • Example#4350 - EventHttp::setDefaultCallback example
  • Example#4351 - EventHttpConnection::makeRequest example
  • Example#4352 - EventHttpConnection::setCloseCallback example
  • Example#4353 - EventHttpRequest::__construct example
  • Example#4354 - EventHttpRequest::sendError example
  • Example#4355 - EventListener::__construct example
  • Example#4356 - EventSslContext::__construct example
  • Example#4357 - FTP-Beispiel
  • Example#4358 - ftp_alloc-Beispiel
  • Example#4359 - ftp_cdup-Beispiel
  • Example#4360 - ftp_chdir-Beispiel
  • Example#4361 - ftp_chmod-Beispiel
  • Example#4362 - ftp_close-Beispiel
  • Example#4363 - ftp_connect-Beispiel
  • Example#4364 - ftp_delete-Beispiel
  • Example#4365 - ftp_exec-Beispiel
  • Example#4366 - ftp_fget-Beispiel
  • Example#4367 - ftp_fput-Beispiel
  • Example#4368 - ftp_get_option-Beispiel
  • Example#4369 - ftp_get-Beispiel
  • Example#4370 - ftp_login-Beispiel
  • Example#4371 - ftp_mdtm-Beispiel
  • Example#4372 - ftp_mkdir-Beispiel
  • Example#4373 - ftp_mlsd-Beispiel
  • Example#4374 - ftp_nb_continue-Beispiel
  • Example#4375 - ftp_nb_fget-Beispiel
  • Example#4376 - ftp_nb_fput-Beispiel
  • Example#4377 - ftp_nb_get-Beispiel
  • Example#4378 - Einen Download mit ftp_nb_get fortsetzen
  • Example#4379 - Einen Download mit Hilfe von ftp_nb_get an Position 100 fortsetzen und in eine neue Datei schreiben
  • Example#4380 - ftp_nb_put-Beispiel
  • Example#4381 - Einen Upload mit ftp_nb_put wieder aufnehmen
  • Example#4382 - ftp_nlist-Beispiel
  • Example#4383 - ftp_pasv-Beispiel
  • Example#4384 - ftp_put-Beispiel
  • Example#4385 - ftp_pwd-Beispiel
  • Example#4386 - ftp_raw für den manuellen Login auf einem FTP-Server nutzen.
  • Example#4387 - ftp_rawlist-Beispiel
  • Example#4388 - ftp_rename-Beispiel
  • Example#4389 - ftp_rmdir-Beispiel
  • Example#4390 - ftp_set_option-Beispiel
  • Example#4391 - Ein SITE-Kommando an einen FTP-Server senden
  • Example#4392 - ftp_size-Beispiel
  • Example#4393 - ftp_ssl_connect-Beispiel
  • Example#4394 - ftp_systype-Beispiel
  • Example#4395 - Basic Gearman client and worker
  • Example#4396 - Basic Gearman client and worker, background
  • Example#4397 - Basic Gearman client and worker, submitting tasks
  • Example#4398 - Adding two job servers
  • Example#4399 - Add two job servers
  • Example#4400 - Basic submission of two tasks
  • Example#4401 - Basic submission of two tasks with passing application context
  • Example#4402 - Two tasks, one background and one not
  • Example#4403 - A high priority task along with two normal tasks
  • Example#4404 - A low priority task along with two normal tasks
  • Example#4405 - Monitor completion of multiple background tasks
  • Example#4406 - Simple job submission with immediate return
  • Example#4407 - Submitting a job and retrieving incremental status
  • Example#4408 - Submit and monitor a background job
  • Example#4409 - Simple job submission with immediate return
  • Example#4410 - Submitting a job and retrieving incremental status
  • Example#4411 - Get the status of a long running job
  • Example#4412 - Monitor the status of a long running background job
  • Example#4413 - Simple worker making use of extra application context data
  • Example#4414 - Add alternate Gearman servers
  • Example#4415 - Add two job servers
  • Example#4416 - GearmanWorker::setId example
  • Example#4417 - A simple worker with a 5 second timeout
  • Example#4418 - Running worker in non-blocking mode
  • Example#4419 - GearmanWorker::work example
  • Example#4420 - Testing support for paged result control
  • Example#4421 - LDAP Such-Beispiel
  • Example#4422 - Binden mit Policy-Informationen
  • Example#4423 - Ändern der Beschreibung, falls diese nicht leer ist
  • Example#4424 - Lesen einiger Werte vor dem Löschen
  • Example#4425 - Löschen einer Referenz
  • Example#4426 - Paginierung für eine Suche verwenden
  • Example#4427 - Komplettes Beispiel mit authentifizierter Verbindung
  • Example#4428 - LDAP Bind verwenden
  • Example#4429 - Anonymes LDAP Bind
  • Example#4430 - Komplettes Beispiel einer Kennwort-Überprüfung
  • Example#4431 - Verbindung zu einem LDAP-Server
  • Example#4432 - Sichere Verbindung zu einem LDAP-Server
  • Example#4433 - LDAP pagination
  • Example#4434 - LDAP pagination
  • Example#4435 - ldap_count_entries-Beispiel
  • Example#4436 - Aufzählung aller LDAP-Fehlermeldungen
  • Example#4437 - Erzeugen und Abfangen eines Fehlers
  • Example#4438 - Searching for an email address
  • Example#4439 - PASSWD extended operation
  • Example#4440 - Whoami extended operation
  • Example#4441 - Anzeigen der Liste der Merkmale für einen ausgewählten Verzeichnis-Eintrag
  • Example#4442 - Prüfen der Protokollversion
  • Example#4443 - Liste alle Werte des Merkmals "mail" für einen Verzeichnis-Eintrag auf
  • Example#4444 - Erzeuge einer Liste aller Organisationseinheiten einer Organisation
  • Example#4445 - Add a telephone number to a contact
  • Example#4446 - Rename a user
  • Example#4447 - Add two e-mail addresses to a user
  • Example#4448 - Change a user's password
  • Example#4449 - Change a user's password (Active Directory)
  • Example#4450 - ldap_parse_result-Beispiel
  • Example#4451 - LDAP-Suche
  • Example#4452 - Setzen der Protokollversion
  • Example#4453 - Setzen der Server-Steuerelemente
  • Example#4454 - LDAP-Sortierung
  • Example#4455 - Memcache Beispiele
  • Example#4456 - Memcache als Session-Handler verwenden
  • Example#4457 - Memcache::add example
  • Example#4458 - Memcache::addServer example
  • Example#4459 - Memcache::close example
  • Example#4460 - Memcache::connect example
  • Example#4461 - Memcache::decrement example
  • Example#4462 - Memcache::delete example
  • Example#4463 - Memcache::flush example
  • Example#4464 - Memcache::get example
  • Example#4465 - Memcache::getExtendedStats example
  • Example#4466 - Memcache::getServerStatus example
  • Example#4467 - Memcache::getVersion example
  • Example#4468 - Memcache::increment example
  • Example#4469 - Memcache::pconnect example
  • Example#4470 - Memcache::replace example
  • Example#4471 - Memcache::set example
  • Example#4472 - Memcache::set example
  • Example#4473 - Memcache::setCompressThreshold example
  • Example#4474 - Memcache::setServerParams example
  • Example#4475 - Result callback example
  • Example#4476 - Read-through callback example
  • Example#4477 - Memcached::addServer example
  • Example#4478 - Memcached::addServers example
  • Example#4479 - Memcached::append example
  • Example#4480 - Memcached::cas example
  • Example#4481 - Creating a Memcached object
  • Example#4482 - Memcached::decrement example
  • Example#4483 - Memcached::delete example
  • Example#4484 - Memcached::fetch example
  • Example#4485 - Memcached::getDelayed example
  • Example#4486 - Memcached::flush example
  • Example#4487 - Memcached::get example #1
  • Example#4488 - Memcached::get example #2
  • Example#4489 - Memcached::getDelayed example
  • Example#4490 - Memcached::getMulti example for Memcached v3
  • Example#4491 - Memcached::getMulti example for Memcached v1 and v2
  • Example#4492 - Memcached::GET_PRESERVE_ORDER example for Memcached v3
  • Example#4493 - Memcached::GET_PRESERVE_ORDER example for Memcached v1 and v2
  • Example#4494 - Retrieving Memcached options
  • Example#4495 - Memcached::getResultCode example
  • Example#4496 - Memcached::getResultMessage example
  • Example#4497 - Memcached::getServerByKey example
  • Example#4498 - Memcached::getServerList example
  • Example#4499 - Memcached::getStats example
  • Example#4500 - Memcached::getVersion example
  • Example#4501 - Memcached::increment example
  • Example#4502 - Memcached::prepend example
  • Example#4503 - Memcached::set example
  • Example#4504 - Memcached::setByKey example
  • Example#4505 - Memcached::setMulti example
  • Example#4506 - Setting a Memcached option
  • Example#4507 - Setting Memcached options
  • Example#4508 - mqseries_back example
  • Example#4509 - mqseries_begin example
  • Example#4510 - mqseries_close example
  • Example#4511 - mqseries_cmit example
  • Example#4512 - mqseries_conn example
  • Example#4513 - mqseries_connx example
  • Example#4514 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4515 - mqseries_disc example
  • Example#4516 - mqseries_get example
  • Example#4517 - mqseries_inq example
  • Example#4518 - mqseries_open example
  • Example#4519 - mqseries_put example
  • Example#4520 - mqseries_strerror example
  • Example#4521 - Benutzung von dns_get_record
  • Example#4522 - Benutzung von dns_get_record und DNS_ANY
  • Example#4523 - fsockopen-Beispiel
  • Example#4524 - Eine UDP-Verbindung nutzen
  • Example#4525 - Ein einfaches gethostbyaddr-Beispiel
  • Example#4526 - Ein einfaches gethostbyname-Beispiel
  • Example#4527 - gethostbynamel-Beispiel
  • Example#4528 - A simple gethostname example
  • Example#4529 - getprotobyname-Beispiel
  • Example#4530 - getservbyname-Beispiel
  • Example#4531 - header_register_callback example
  • Example#4532 - Unsetting specific header.
  • Example#4533 - Unsetting all previously set headers.
  • Example#4534 - Download-Dialog
  • Example#4535 - Caching-Direktiven
  • Example#4536 - Setzen eines Cookies
  • Example#4537 - Beispiel zur Verwendung von headers_list
  • Example#4538 - Beispiel zur Verwendung von headers_sent
  • Example#4539 - Using http_response_code in a web server environment
  • Example#4540 - Using http_response_code in a CLI environment
  • Example#4541 - inet_ntop-Beispiel
  • Example#4542 - inet_pton-Beispiel
  • Example#4543 - ip2long-Beispiel:
  • Example#4544 - Eine IP-Adresse anzeigen
  • Example#4545 - setcookie-Beispiele
  • Example#4546 - setcookie-Beispiele zum Löschen
  • Example#4547 - setcookie und Arrays
  • Example#4548 - Die Verwendung von syslog
  • Example#4549 - Procedural usage of rrd
  • Example#4550 - OO usage of rrd
  • Example#4551 - RRDGraph::setOptions example
  • Example#4552 - Set multiple color options
  • Example#4553 - RRDUpdater::update examples
  • Example#4554 - Fetch instrumented calls
  • Example#4555 - Fetch the list of functions scoutapm will instrument
  • Example#4556 - snmp_get_quick_print-Beispiel
  • Example#4557 - Using snmp_get_valueretrieval
  • Example#4558 - Using snmp_read_mib
  • Example#4559 - Using snmp_set_enum_print
  • Example#4560 - Using snmprealwalk
  • Example#4561 - Verwendung von snmp_set_quick_print
  • Example#4562 - Using snmp_set_valueretrieval
  • Example#4563 - Using snmp2_get
  • Example#4564 - Using snmp2_get_next
  • Example#4565 - Using snmp2_real_walk
  • Example#4566 - Using snmp2_set
  • Example#4567 - Using snmp2_set for setting BITS SNMP object id
  • Example#4568 - snmp2_walk Example
  • Example#4569 - Using snmp3_get
  • Example#4570 - Using snmp3_getnext
  • Example#4571 - Using snmp3_real_walk
  • Example#4572 - Using snmp3_set
  • Example#4573 - Using snmp3_set for setting BITS SNMP object id
  • Example#4574 - snmp3_walk Example
  • Example#4575 - Verwendung von snmpget
  • Example#4576 - Using snmpgetnext
  • Example#4577 - Using snmprealwalk
  • Example#4578 - Verwendung von snmpset
  • Example#4579 - Verwendung von snmpset zum Setzen von BITS-SNMP-Objektkennungen
  • Example#4580 - snmpwalk-Beispiel
  • Example#4581 - snmpwalkoid-Beispiel
  • Example#4582 - SNMP::close example
  • Example#4583 - Fetching sysLocation
  • Example#4584 - Single SNMP object
  • Example#4585 - Multiple SNMP objects
  • Example#4586 - SNMP::getErrno example
  • Example#4587 - SNMP::getError example
  • Example#4588 - Single SNMP object
  • Example#4589 - Miltiple SNMP objects
  • Example#4590 - Set single SNMP object id
  • Example#4591 - Set multiple values using single SNMP::set call
  • Example#4592 - Using SNMP::set for setting BITS SNMP object id
  • Example#4593 - SNMP::setSecurity example
  • Example#4594 - SNMP::walk example
  • Example#4595 - suffixAsKey example
  • Example#4596 - Socket-Beispiel: Einfacher TCP/IP-Server
  • Example#4597 - Socket-Beispiel: Einfacher TCP/IP-Client
  • Example#4598 - Using socket_atmark to set the source address
  • Example#4599 - Beispiel: Quell-Adresse setzen mit socket_bind
  • Example#4600 - socket_create_pair-Beispiel
  • Example#4601 - socket_create_pair-IPC-Beispiel
  • Example#4602 - socket_get_option-Beispiel
  • Example#4603 - socket_import_stream example
  • Example#4604 - socket_last_error-Beispiel
  • Example#4605 - socket_recv-Beispiel
  • Example#4606 - socket_recvfrom-Beispiel
  • Example#4607 - null mit socket_select benutzen:
  • Example#4608 - Rückgaben von socket_select verstehen
  • Example#4609 - socket_select-Beispiel
  • Example#4610 - socket_sendto-Beispiel
  • Example#4611 - socket_set_block-Beispiel
  • Example#4612 - socket_set_nonblock-Beispiel
  • Example#4613 - socket_set_option-Beispiel
  • Example#4614 - socket_strerror-Beispiel
  • Example#4615 - Authenticating with a ssh agent
  • Example#4616 - Authentication using a public hostkey
  • Example#4617 - Retrieving a list of authentication methods
  • Example#4618 - Authenticating with a password
  • Example#4619 - Authentication using a public key
  • Example#4620 - ssh2_connect example
  • Example#4621 - Executing a command
  • Example#4622 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4623 - Checking the fingerprint against a known value
  • Example#4624 - Determining what methods were negotiated
  • Example#4625 - Adding a publickey with ssh2_publickey_add
  • Example#4626 - Listing authorized keys with ssh2_publickey_list
  • Example#4627 - Downloading a file via SCP
  • Example#4628 - Uploading a file via SCP
  • Example#4629 - Changing the mode of a file on a remote server
  • Example#4630 - Stating a symbolic link via SFTP
  • Example#4631 - Creating a directory on a remote server
  • Example#4632 - Reading a symbolic link
  • Example#4633 - Resolving a pathname
  • Example#4634 - Renaming a file via sftp
  • Example#4635 - Removing a directory on a remote server
  • Example#4636 - Stating a file via SFTP
  • Example#4637 - Creating a symbolic link
  • Example#4638 - Deleting a file
  • Example#4639 - Opening a file via SFTP
  • Example#4640 - Requesting an interactive shell
  • Example#4641 - Opening a tunnel to an arbitrary host
  • Example#4642 - Objektorientierter Stil
  • Example#4643 - Prozeduraler Stil
  • Example#4644 - stomp_connect_error example
  • Example#4645 - stomp_version example
  • Example#4646 - Objektorientierter Stil
  • Example#4647 - Prozeduraler Stil
  • Example#4648 - Objektorientierter Stil
  • Example#4649 - Prozeduraler Stil
  • Example#4650 - Objektorientierter Stil
  • Example#4651 - Prozeduraler Stil
  • Example#4652 - Objektorientierter Stil
  • Example#4653 - Prozeduraler Stil
  • Example#4654 - Objektorientierter Stil
  • Example#4655 - Prozeduraler Stil
  • Example#4656 - Objektorientierter Stil
  • Example#4657 - Prozeduraler Stil
  • Example#4658 - Objektorientierter Stil
  • Example#4659 - Prozeduraler Stil
  • Example#4660 - Objektorientierter Stil
  • Example#4661 - Prozeduraler Stil
  • Example#4662 - Objektorientierter Stil
  • Example#4663 - Prozeduraler Stil
  • Example#4664 - Train from array
  • Example#4665 - Train from a file
  • Example#4666 - svn_add example
  • Example#4667 - Default authentication example
  • Example#4668 - svn_blame example
  • Example#4669 - Basic example
  • Example#4670 - Basic example
  • Example#4671 - Basic example
  • Example#4672 - Basic example
  • Example#4673 - Basic example
  • Example#4674 - Basic example
  • Example#4675 - Diffing two revisions of a repository path
  • Example#4676 - Portably diffing two local files
  • Example#4677 - svn_export example
  • Example#4678 - Basic example
  • Example#4679 - svn_log example
  • Example#4680 - svn_ls example
  • Example#4681 - Basic example
  • Example#4682 - Basic example
  • Example#4683 - Deny all connections from localhost
  • Example#4684 - Ban an URL
  • Example#4685 - Get statistic snapshot
  • Example#4686 - Read varnish shared memory log
  • Example#4687 - VarnishAdmin::__construct example
  • Example#4688 - Parallel searching using Yaz
  • Example#4689 - CCL configuration
  • Example#4690 - CCL Parsing
  • Example#4691 - Record Update
  • Example#4692 - Array for GRS-1 record
  • Example#4693 - Working with MARCXML
  • Example#4694 - PHP function that scans titles
  • Example#4695 - Query Examples
  • Example#4696 - Sort Criterias
  • Example#4697 - A ZMQContext example
  • Example#4698 - A ZMQContext example
  • Example#4699 - A ZMQContext example
  • Example#4700 - A ZMQSocket example
  • Example#4701 - A send/recv example
  • Example#4702 - A ZMQPoll example
  • Example#4703 - zookeeper_dispatch example #1
  • Example#4704 - zookeeper_dispatch example #2
  • Example#4705 - Zookeeper::addAuth example
  • Example#4706 - Zookeeper::create example
  • Example#4707 - Zookeeper::delete example
  • Example#4708 - Zookeeper::exists example
  • Example#4709 - Zookeeper::get example
  • Example#4710 - Zookeeper::get stat example
  • Example#4711 - Zookeeper::getAcl example
  • Example#4712 - Zookeeper::getChildren example
  • Example#4713 - Zookeeper::set example
  • Example#4714 - Zookeeper::setAcl example
  • Example#4715 - Zookeeper::setDebugLevel example
  • Example#4716 - ZookeeperConfig::add example
  • Example#4717 - ZookeeperConfig::get example
  • Example#4718 - ZookeeperConfig::remove example
  • Example#4719 - ZookeeperConfig::set example
  • Example#4720 - solr_get_version example
  • Example#4721 - Inhalt der BootStrap-Datei
  • Example#4722 - Hinzufügen eines Dokuments zum Index
  • Example#4723 - Zusammenführen eines Dokuments in ein anderes Dokument
  • Example#4724 - Suche nach Dokumenten - SolrObject-Antworten
  • Example#4725 - Suche nach Dokumenten - SolrDocument-Antworten
  • Example#4726 - Einfaches TermsComponent-Beispiel - grundlegend
  • Example#4727 - Einfaches TermsComponent-Beispiel - Verwendung eines Präfixes
  • Example#4728 - Einfaches TermsComponent-Beispiel - Festlegen einer Mindesthäufigkeit
  • Example#4729 - Einfaches Facet-Beispiel
  • Example#4730 - Einfaches Facet-Beispiel - mit optionalem Überschreiben des Feldes für mincount
  • Example#4731 - Facet Date-Beispiel
  • Example#4732 - Verbindung zu einem SSL-fähigen Server herstellen
  • Example#4733 - Zusammenfassen eines SolrQuery
  • Example#4734 - Solr Real Time Get (RTG)-Beispiel SolrClient::getById
  • Example#4735 - SolrInputDocument::addChildDocument example
  • Example#4736 - SolrInputDocument::addChildDocuments example
  • Example#4737 - SolrDocument::toArray example
  • Example#4738 - SolrObject::__construct example
  • Example#4739 - SolrObject::offsetUnset example
  • Example#4740 - SolrClient::addDocument example
  • Example#4741 - SolrClient::addDocument example 2
  • Example#4742 - SolrClient::addDocuments example
  • Example#4743 - SolrClient::__construct example
  • Example#4744 - SolrQuery::deleteByQuery example
  • Example#4745 - SolrClient::getById example
  • Example#4746 - SolrClient::getByIds example
  • Example#4747 - SolrClient::ping example
  • Example#4748 - SolrClient::query example
  • Example#4749 - SolrClient::request example
  • Example#4750 - SolrClient::setResponseWriter example
  • Example#4751 - SolrParams::setParam example
  • Example#4752 - SolrQuery::addFacetField example
  • Example#4753 - SolrQuery::addFacetField example
  • Example#4754 - SolrQuery::addFilterQuery example
  • Example#4755 - SolrQuery::addGroupSortField example
  • Example#4756 - SolrQuery::collapse example
  • Example#4757 - SolrQuery::setExpand example
  • Example#4758 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4759 - SolrDisMaxQuery::addBoostQuery example
  • Example#4760 - SolrDisMaxQuery::addPhraseField example
  • Example#4761 - SolrDisMaxQuery::addQueryField example
  • Example#4762 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4763 - SolrDisMaxQuery::addUserField example
  • Example#4764 - SolrDisMaxQuery::__construct example
  • Example#4765 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4766 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4767 - SolrDisMaxQuery::removePhraseField example
  • Example#4768 - SolrDisMaxQuery::removeQueryField example
  • Example#4769 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4770 - SolrDisMaxQuery::removeUserField example
  • Example#4771 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4772 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4773 - SolrDisMaxQuery::setBoostFunction example
  • Example#4774 - SolrDisMaxQuery::setBoostQuery example
  • Example#4775 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4776 - SolrDisMaxQuery::setPhraseFields example
  • Example#4777 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4778 - SolrDisMaxQuery::setQueryAlt example
  • Example#4779 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4780 - SolrDisMaxQuery::setTieBreaker example
  • Example#4781 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4782 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4783 - SolrDisMaxQuery::setUserFields example
  • Example#4784 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4785 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4786 - SolrCollapseFunction::__construct example
  • Example#4787 - SolrCollapseFunction::setHint example
  • Example#4788 - SolrCollapseFunction::setMax example
  • Example#4789 - Parsen von PHP für ein Verzeichnis ausschalten mittels .htaccess
  • Example#4790 - apache_get_modules-Beispiel
  • Example#4791 - apache_get_version-Beispiel
  • Example#4792 - apache_getenv-Beispiel
  • Example#4793 - apache_lookup_uri-Beispiel
  • Example#4794 - Übergeben von Informationen zwischen PHP und Perl
  • Example#4795 - Werte in access.log aufzeichnen
  • Example#4796 - apache_request_headers-Beispiel
  • Example#4797 - apache_response_headers-Beispiel
  • Example#4798 - Eine Apache-Umgebungsvariable mit apache_setenv setzen
  • Example#4799 - getallheaders-Beispiel
  • Example#4800 - Registrierung einer Variablen mit $_SESSION.
  • Example#4801 - Aufheben der Registrierung einer Variablen mit $_SESSION.
  • Example#4802 - Zählen der Seitenaufrufe eines einzelnen Benutzers
  • Example#4803 - Beispiel-Informationen
  • Example#4804 - session_cache_expire-Beispiel
  • Example#4805 - session_cache_limiter-Beispiel
  • Example#4806 - session_create_id-Beispiel mit session_regenerate_id
  • Example#4807 - Löschen einer Session mit $_SESSION
  • Example#4808 - session_gc-Beispiel für Taskmanager wie cron
  • Example#4809 - session_gc-Beispiel für ein Skript, auf das ein Benutzer Zugriff hat
  • Example#4810 - session_name-Beispiel
  • Example#4811 - Ein session_regenerate_id-Beispiel
  • Example#4812 - Verhindern von verlorenen Sessions durch session_regenerate_id
  • Example#4813 - Benutzerdefierte Session-Routine; der vollständige Code ist bei SessionHandlerInterface aufgeführt
  • Example#4814 - seite1.php
  • Example#4815 - seite2.php
  • Example#4816 - Die Cookie-Gültigkeitsdauer übersteuern
  • Example#4817 - Die Session lesen und schließen
  • Example#4818 - Die Verwendung von SessionHandler, um den internen PHP-Speicherverwalter mit Verschlüsselung zu versehen
  • Example#4819 - Ein Beispiel mit SessionHandlerInterface
  • Example#4820 - Tokenize comma separated integer list
  • Example#4821 - Tokenize assign statement
  • Example#4822 - Simple calculator
  • Example#4823 - Parse words out from a sentence
  • Example#4824 - Beispiele gültiger Suchmuster
  • Example#4825 - Beispiele ungültiger Suchmuster
  • Example#4826 - Usage of comments in PCRE pattern
  • Example#4827 - Beispiel zum Vergleich von preg_filter und preg_replace
  • Example#4828 - preg_grep-Beispiel
  • Example#4829 - preg_last_error_msg example
  • Example#4830 - preg_last_error-Beispiel
  • Example#4831 - Alle Telefonnummern aus einem Text holen.
  • Example#4832 - Zusammengehörende HTML-Tags finden (gierig)
  • Example#4833 - Benannte Teilsuchmuster (named subpatterns)
  • Example#4834 - Die Zeichenkette "php" finden
  • Example#4835 - Die Zeichenkette "web" finden
  • Example#4836 - Den Domänen-Namen aus einer URL holen
  • Example#4837 - Benannte Teilsuchmuster (named subpatterns)
  • Example#4838 - preg_quote-Beispiel
  • Example#4839 - Kursivdruck eines Wortes in einem Text
  • Example#4840 - preg_replace_callback_array example
  • Example#4841 - preg_replace_callback und Anonyme Funktion
  • Example#4842 - preg_replace_callback-Beispiel
  • Example#4843 - preg_replace_callback unter Verwendung einer rekursiven Struktur um gekapselten BB-Code zu verarbeiten
  • Example#4844 - Die Verwendung von Rückreferenzierungen mit darauf folgenden numerischen Literalen
  • Example#4845 - Die Verwendung von preg_replace mit indizierten Arrays
  • Example#4846 - Ersetzen mehrerer Werte
  • Example#4847 - Leerzeichen entfernen
  • Example#4848 - Die Verwendung des Parameters count
  • Example#4849 - preg_split-Beispiel: Eine Zeichenkette in Teile zerlegen
  • Example#4850 - Eine Zeichenkette in einzelne Zeichen zerlegen
  • Example#4851 - Zerlegen einer Zeichenkette in Suchtreffer und Erfassen der Positionen
  • Example#4852 - addcslashes-Beispiel
  • Example#4853 - Ein addslashes-Beispiel
  • Example#4854 - bin2hex-Beispiel
  • Example#4855 - chr-Beispiel
  • Example#4856 - Überlauf-Verhalten
  • Example#4857 - Erstellen einer UTF-8-Zeichenkette aus einzelnen Bytes
  • Example#4858 - chunk_split-Beispiel
  • Example#4859 - convert_uudecode-Beispiel
  • Example#4860 - convert_uuencode-Beispiel
  • Example#4861 - count_chars-Beispiel
  • Example#4862 - Anzeigen einer CRC32-Prüfsumme
  • Example#4863 - crypt-Beispiele
  • Example#4864 - echo-Beispiele
  • Example#4865 -
  • Example#4866 - explode-Beispiele
  • Example#4867 - explode-Rückgabebeispiele
  • Example#4868 - limit-Parameterbeispiele
  • Example#4869 - fprintf: Integer mit vorangestellten Nullen
  • Example#4870 - fprintf: Formatieren einer Währung
  • Example#4871 - Beispiel für eine Umwandlungstabelle
  • Example#4872 - hex2bin-Beispiel
  • Example#4873 - Dekodieren benannter HTML-Zeichen
  • Example#4874 - Ein htmlentities-Beispiel
  • Example#4875 - Verwendung von ENT_IGNORE
  • Example#4876 - Ein htmlspecialchars_decode-Beispiel
  • Example#4877 - htmlspecialchars-Beispiel
  • Example#4878 - implode-Beispiel
  • Example#4879 - lcfirst-Beispiel
  • Example#4880 - levenshtein-Beispiel
  • Example#4881 - localeconv-Beispiel
  • Example#4882 - Beispiel zur Verwendung von ltrim
  • Example#4883 - Anwendungsbeispiel für md5_file
  • Example#4884 - Ein md5-Beispiel
  • Example#4885 - Einfaches metaphone-Beispiel
  • Example#4886 - Verwendung des max_phonemes-Parameters
  • Example#4887 - Verwendung des max_phonemes-Parameters
  • Example#4888 - money_format-Beispiel
  • Example#4889 - nl_langinfo-Beispiel
  • Example#4890 - Verwenden von nl2br
  • Example#4891 - Erstellen von validem HTML-Markup unter Verwendung des use_xhtml-Parameters
  • Example#4892 - Verschiedene Zeilentrenner
  • Example#4893 - number_format-Beispiel
  • Example#4894 - ord-Beispiel
  • Example#4895 - Untersuchen der einzelnen Bytes einer UTF-8-Zeichenkette
  • Example#4896 - Der Gebrauch von parse_str
  • Example#4897 - parse_str-Namens-Manipulation
  • Example#4898 - print-Beispiele
  • Example#4899 -
  • Example#4900 -
  • Example#4901 - printf: Verschiedene Beispiele
  • Example#4902 - printf: Stringformatierung
  • Example#4903 - quoted_printable_decode-Beispiel
  • Example#4904 - quoted_printable_encode-Beispiel
  • Example#4905 - quotemeta-Beispiel
  • Example#4906 - Beispiel zur Verwendung von rtrim
  • Example#4907 - setlocale-Beispiele
  • Example#4908 - setlocale-Beispiele for Windows
  • Example#4909 - sha1_file-Beispiel
  • Example#4910 - Ein sha1-Beispiel
  • Example#4911 - Beispiel für die Vertauschung der Argumente von similar_text
  • Example#4912 - Soundex-Beispiele
  • Example#4913 - Argumente tauschen
  • Example#4914 - Angabe von Füllzeichen
  • Example#4915 - Positionstausch mit weiteren Spezifikatoren
  • Example#4916 - sprintf: Mit Nullen aufgefüllte Integer
  • Example#4917 - sprintf: Währungsformatierung
  • Example#4918 - sprintf: Wissenschaftliche Notation
  • Example#4919 - sscanf-Beispiel
  • Example#4920 - sscanf - Verwendung optionaler Parameter
  • Example#4921 - Using the empty string ''
  • Example#4922 - Showing case-sensitivity
  • Example#4923 - Basic str_decrement example
  • Example#4924 - str_decrement example with a carry
  • Example#4925 - Using the empty string ''
  • Example#4926 - Showing case-sensitivity
  • Example#4927 - str_getcsv-Beispiel
  • Example#4928 - str_getcsv-Beispiel mit einer leeren Zeichenkette
  • Example#4929 - Basic str_increment example
  • Example#4930 - str_increment example with a carry
  • Example#4931 - str_ireplace-Beispiel
  • Example#4932 - str_pad-Beispiel
  • Example#4933 - str_repeat-Beispiel
  • Example#4934 - Grundlegende str_replace-Beispiele
  • Example#4935 - Beispiele möglicher Probleme durch str_replace
  • Example#4936 - str_rot13-Beispiel
  • Example#4937 - str_shuffle-Beispiel
  • Example#4938 - Beispiel für die Verwendung von str_split
  • Example#4939 - Using the empty string ''
  • Example#4940 - Showing case-sensitivity
  • Example#4941 - Ein str_word_count-Beispiel
  • Example#4942 - strcasecmp-Beispiel
  • Example#4943 - strcmp-Beispiel
  • Example#4944 - strcspn-Beispiel
  • Example#4945 - strip_tags-Beispiel
  • Example#4946 - stripcslashes-Beispiel
  • Example#4947 - stripos-Beispiele
  • Example#4948 - Ein stripslashes-Beispiel
  • Example#4949 - Verwendung von stripslashes in einem Array
  • Example#4950 - stristr-Beispiel
  • Example#4951 - Prüfen, ob ein String gefunden wurde oder nicht
  • Example#4952 - Verwendung eines Wertes, der kein String ist
  • Example#4953 - Ein strlen-Beispiel
  • Example#4954 - strnatcasecmp-Beispiel
  • Example#4955 - strncasecmp-Beispiel
  • Example#4956 - strncmp-Beispiel
  • Example#4957 - strpbrk-Beispiel
  • Example#4958 - Verwendung von ===
  • Example#4959 - Verwendung von !==
  • Example#4960 - Verwendung eines Offsets
  • Example#4961 - strrchr-Beispiel
  • Example#4962 - Umkehren eines Strings mit strrev
  • Example#4963 - Ein einfaches strripos-Beispiel
  • Example#4964 - Prüfen ob needle in haystack vorkommt
  • Example#4965 - Mit Offsets suchen
  • Example#4966 - strspn-Beispiel
  • Example#4967 - strstr-Beispiel
  • Example#4968 - strtok-Beispiel
  • Example#4969 - Verhalten von strtok beim Auffinden eines leeren Teils
  • Example#4970 - Der Unterschied zwischen strtok und explode
  • Example#4971 - strtolower-Beispiel
  • Example#4972 - strtoupper-Beispiel
  • Example#4973 - strtr-Beispiel
  • Example#4974 - strtr-Beispiel mit zwei Argumenten
  • Example#4975 - strtr: Vergleich der Verhaltensweisen
  • Example#4976 - Ein substr_compare-Beispiel
  • Example#4977 - Ein substr_count-Beispiel
  • Example#4978 - Einfache substr_replace-Beispiele
  • Example#4979 - Nutzung von substr_replace um mehrere Zeichenketten auf einmal zu ersetzen.
  • Example#4980 - Einen negativen offset-Wert verwenden
  • Example#4981 - Negativen length-Wert verwenden
  • Example#4982 - Generelle Verwendung von substr
  • Example#4983 - substr-Typumwandlungs-Verhalten
  • Example#4984 - Ungültiger Zeichenbereich
  • Example#4985 - Beispiel zur Verwendung von trim
  • Example#4986 - Trimmen von Array-Werten mittels trim
  • Example#4987 - ucfirst-Beispiel
  • Example#4988 - ucwords-Beispiel
  • Example#4989 - ucwords-Beispiel mit benutzerdefinierten Trenzeichen
  • Example#4990 - ucwords-Beispiel mit zusätzlichen Trennzeichen
  • Example#4991 - Grundlegende Beispiele
  • Example#4992 - Grundlegendes Beispiel
  • Example#4993 - vfprintf: Integer-Werte mit führenden Nullen
  • Example#4994 - vprintf: mit Nullen aufgefüllte Ganzzahlen
  • Example#4995 - vsprintf: mit Nullen aufgefüllte Ganzzahlen
  • Example#4996 - wordwrap-Beispiel
  • Example#4997 - wordwrap-Beispiel
  • Example#4998 - wordwrap-Beispiel
  • Example#4999 - array_change_key_case-Beispiel
  • Example#5000 - array_chunk-Beispiel
  • Example#5001 - Auslesen der Spalte der Vornamen aus einem Datensatz
  • Example#5002 - Abrufen der Spalte der Nachnamen aus einem Datensatz, indiziert durch die Spalte "id"
  • Example#5003 - Abrufen der Spalte mit den Benutzernamen aus der öffentlichen Eigenschaft "username" eines Objekts
  • Example#5004 - Abrufen der Spalte der Namen aus der privaten Eigenschaft "name" eines Objekts mit der magischen Methode __get
  • Example#5005 - Ein einfaches array_combine-Beispiel
  • Example#5006 - array_count_values-Beispiel
  • Example#5007 - array_diff_assoc-Beispiel
  • Example#5008 - array_diff_assoc-Beispiel
  • Example#5009 - array_diff_key-Beispiel
  • Example#5010 - array_diff_uassoc-Beispiel
  • Example#5011 - array_diff_ukey-Beispiel
  • Example#5012 - array_diff-Beispiel
  • Example#5013 - array_diff-Beispiel mit nicht übereinstimmenden Typen
  • Example#5014 - array_fill_keys-Beispiel
  • Example#5015 - array_fill-Beispiel
  • Example#5016 - array_fill-Beispiel mit einem negativen Startindex
  • Example#5017 - array_filter-Beispiel
  • Example#5018 - array_filter ohne callback
  • Example#5019 - array_filter mit mode
  • Example#5020 - array_flip-Beispiel
  • Example#5021 - array_flip-Beispiel: Kollision
  • Example#5022 - array_intersect_assoc-Beispiel
  • Example#5023 - array_intersect_key-Beispiel
  • Example#5024 - array_intersect_uassoc-Beispiel
  • Example#5025 - array_intersect_ukey-Beispiel
  • Example#5026 - array_intersect-Beispiel
  • Example#5027 - array_is_list-Beispiel
  • Example#5028 - array_key_exists-Beispiel
  • Example#5029 - array_key_exists vs. isset
  • Example#5030 - Grundlegende Verwendung von array_key_first
  • Example#5031 - array_keys-Beispiel
  • Example#5032 - array_map-Beispiel
  • Example#5033 - array_map mit einer Lambda-Funktion
  • Example#5034 - array_map - Verwendung mehrerer Arrays
  • Example#5035 - Durchführen einer zip-Operation von Arrays
  • Example#5036 - null-callback mit nur einem array
  • Example#5037 - array_map - mit String-Schlüsseln
  • Example#5038 - array_map - assoziative Arrays
  • Example#5039 - array_merge_recursive-Beispiel
  • Example#5040 - array_merge-Beispiel
  • Example#5041 - Ein einfaches array_merge-Beispiel
  • Example#5042 - array_merge mit nicht-Array-Typen
  • Example#5043 - Sortieren mehrerer Arrays
  • Example#5044 - Sortieren eines mehrdimensionalen Arrays
  • Example#5045 - Datenbankdaten sortieren
  • Example#5046 - Groß-/Kleinschreibung nicht-beachtende Sortierung
  • Example#5047 - array_pad-Beispiel
  • Example#5048 - array_pop-Beispiel
  • Example#5049 - array_product-Beispiele
  • Example#5050 - array_push Beispiel
  • Example#5051 - array_rand-Beispiel
  • Example#5052 - array_reduce-Beispiel
  • Example#5053 - array_replace_recursive-Beispiel
  • Example#5054 - array_replace_recursive und rekursives Verhalten
  • Example#5055 - array_replace Beispiel
  • Example#5056 - array_reverse-Beispiel
  • Example#5057 - array_search-Beispiel
  • Example#5058 - array_shift-Beispiel
  • Example#5059 - array_slice-Beispiele
  • Example#5060 - array_slice und ein mit 1 beginnendes Array
  • Example#5061 - array_slice und Array mit gemischten Schlüsseln
  • Example#5062 - array_splice-Beispiele
  • Example#5063 - array_splice-Beispiele zu gleichwertigen Anweisungen
  • Example#5064 - array_sum-Beispiele
  • Example#5065 - array_udiff_assoc-Beispiel
  • Example#5066 - array_udiff_uassoc-Beispiel
  • Example#5067 - array_udiff Beispiel mit stdClass Objekten
  • Example#5068 - array_udiff Beispiel mit DateTime Objekten
  • Example#5069 - array_uintersect_assoc Beispiel
  • Example#5070 - array_uintersect_uassoc Beispiel
  • Example#5071 - array_uintersect Beispiel
  • Example#5072 - array_unique-Beispiel
  • Example#5073 - array_unique und Typen
  • Example#5074 - array_unshift-Beispiel
  • Example#5075 - Verwendung mit assoziativen Arrays
  • Example#5076 - array_values-Beispiel
  • Example#5077 - array_walk_recursive Beispiel
  • Example#5078 - array_walk-Beispiel
  • Example#5079 - array_walk-Beispiel mit einer anonymen Funktion
  • Example#5080 - array-Beispiel
  • Example#5081 - Automatischer Index mit array
  • Example#5082 - 1-basierter Index mit array
  • Example#5083 - Auf ein Array innerhalb von doppelten Anführungszeichen zugreifen
  • Example#5084 - arsort-Beispiel
  • Example#5085 - asort-Beispiel
  • Example#5086 - compact-Beispiel
  • Example#5087 - count-Beispiel
  • Example#5088 - count-Beispiel für ein nicht zählbares Array (schlechtes Beispiel - nicht verwenden)
  • Example#5089 - Rekursives count-Beispiel
  • Example#5090 - Countable-Objekt
  • Example#5091 - Beispiel für die Verwendung von current und Freunden
  • Example#5092 - each-Beispiele
  • Example#5093 - Durchlaufen eines Arrays mit each
  • Example#5094 - end-Beispiel
  • Example#5095 - extract-Beispiel
  • Example#5096 - in_array-Beispiel
  • Example#5097 - in_array-Beispiel mit 'strict'
  • Example#5098 - in_array mit Array als Suchwert
  • Example#5099 - key-Beispiel
  • Example#5100 - krsort-Beispiel
  • Example#5101 - ksort-Beispiel
  • Example#5102 - ksort mit int-Schlüsseln
  • Example#5103 - list-Beispiele
  • Example#5104 - Ein Beispiel für die Verwendung von list
  • Example#5105 - Verschachtelte list-Ausdrücke verwenden
  • Example#5106 - list und die Reihenfolge der Index-Definitionen
  • Example#5107 - list mit Schlüsseln
  • Example#5108 - natcasesort-Beispiel
  • Example#5109 - Beispiele für die grundlegende Verwendung von natsort
  • Example#5110 - natsort-Beispiele, die potentielle Tücken demonstrieren
  • Example#5111 - Beispiel für die Verwendung von next und Freunden
  • Example#5112 - Beispiel für die Verwendung von prev und Freunden
  • Example#5113 - range-Beispiele
  • Example#5114 - reset-Beispiel
  • Example#5115 - rsort-Beispiel
  • Example#5116 - shuffle-Beispiel
  • Example#5117 - sort-Beispiel
  • Example#5118 - sort-Beispiel mit natürlicher Sortierung ohne Beachtung der Groß- und Kleinschreibung
  • Example#5119 - Einfaches uasort-Beispiel
  • Example#5120 - uksort-Beispiel
  • Example#5121 - usort-Beispiel
  • Example#5122 - usort-Beispiel für mehrdimensionale Arrays
  • Example#5123 - usort-Beispiel, das die Methode eines Objekts benutzt
  • Example#5124 - usort-Beispiel zum Einsatz einer Closure zum Sortieren eines mehrdimensionalen Arrays
  • Example#5125 - usort Beispiel unter Verwendung des Raumschiff-Operators
  • Example#5126 - Klassendefinitionen
  • Example#5127 - test_script.php
  • Example#5128 - class_alias-Beispiel
  • Example#5129 - class_exists-Beispiel
  • Example#5130 - autoload-Parameter-Beispiel
  • Example#5131 - enum_exists-Beispiel
  • Example#5132 - Die Verwendung von get_called_class
  • Example#5133 - get_class_methods-Beispiel
  • Example#5134 - get_class_vars Beispiel
  • Example#5135 - get_class_vars und geltungsbereichsabhängiges Verhalten
  • Example#5136 - get_class-Beispiel
  • Example#5137 - Einsatz von get_class in einer Elternklasse
  • Example#5138 - Verwendung von get_class mit Klassen in Namensräumen
  • Example#5139 - get_declared_classes-Beispiel
  • Example#5140 - get_declared_interfaces Beispiel
  • Example#5141 - get_mangled_object_vars-Beispiel
  • Example#5142 - Nutzung der get_object_vars-Funktion
  • Example#5143 - Die Verwendung von get_parent_class
  • Example#5144 - interface_exists-Beispiel
  • Example#5145 - is_a-Beispiel
  • Example#5146 - Verwendung des instanceof-Operators
  • Example#5147 - is_subclass_of Beispiel
  • Example#5148 - Verwendung von is_subclass_of mit einem Interface
  • Example#5149 - method_exists Beispiel
  • Example#5150 - Statisches method_exists Beispiel
  • Example#5151 - Ein property_exists-Beispiel
  • Example#5152 - ctype_alnum-Beispiel (unter Verwendung der Standard-Locale)
  • Example#5153 - ctype_alpha-Beispiel (unter Verwendung der Standard-Locale)
  • Example#5154 - ctype_cntrl-Beispiel
  • Example#5155 - ctype_digit-Beispiel
  • Example#5156 - ctype_digit-Beispiel für den Vergleich von Strings mit ganzen Zahlen
  • Example#5157 - ctype_graph-Beispiel
  • Example#5158 - ctype_lower-Beispiel (unter Verwendung der Standard-Locale)
  • Example#5159 - ctype_print-Beispiel
  • Example#5160 - ctype_punct-Beispiel
  • Example#5161 - ctype_space-Beispiel
  • Example#5162 - ctype_upper-Beispiel (unter Verwendung der Standard-Locale)
  • Example#5163 - ctype_xdigit-Beispiel
  • Example#5164 - Den Standardfilters so einstellen, dass er sich wie htmlspecialchars verhält
  • Example#5165 - Den Standardfilter so konfigurieren, dass er sich wie htmlspecialchars verhält
  • Example#5166 - Validating email addresses with filter_var
  • Example#5167 - Validating IP addresses with filter_var
  • Example#5168 - Passing options to filter_var
  • Example#5169 - Sanitizing and validating email addresses
  • Example#5170 - Configuring a default filter
  • Example#5171 - filter_input_array Beispiel
  • Example#5172 - filter_input Beispiel
  • Example#5173 - filter_list-Beispiel
  • Example#5174 - filter_var_array-Beispiel
  • Example#5175 - filter_var-Beispiel
  • Example#5176 - Beispiel für das Filtern eines Arrays
  • Example#5177 - call_user_func_array example
  • Example#5178 - call_user_func_array using namespace name
  • Example#5179 - Using lambda function
  • Example#5180 - Passing values by reference
  • Example#5181 - call_user_func_array using named arguments
  • Example#5182 - call_user_func-Beispiel und Referenzen
  • Example#5183 - call_user_func-Beispiel
  • Example#5184 - call_user_func mit Namensraum-Namen
  • Example#5185 - Verwenden einer Klassenmethode mit call_user_func
  • Example#5186 - Verwendung von Lambdafunktionen mit call_user_func
  • Example#5187 - Dynamisches Erzeugen einer Funktion, mit create_function oder anonymen Funktionen
  • Example#5188 - Erstellen einer allgemeinen Verarbeitungsfunktion mit create_function oder anonymen Funktionen
  • Example#5189 - Gebrauch der anonymen Funktionen als Callback-Funktion
  • Example#5190 - forward_static_call_array example
  • Example#5191 - forward_static_call example
  • Example#5192 - func_get_arg-Beispiel
  • Example#5193 - func_get_arg-Beispiel zu byref- und byval-Argumenten
  • Example#5194 - func_get_args-Beispiel
  • Example#5195 - func_get_args-Beispiel mit Referenz- und Wert-Argumenten
  • Example#5196 - func_num_args-Beispiel
  • Example#5197 - function_exists-Beispiel
  • Example#5198 - get_defined_functions-Beispiel
  • Example#5199 - register_shutdown_function-Beispiel
  • Example#5200 - register_tick_function example
  • Example#5201 - Quickhash Example
  • Example#5202 - Quickhash ArrayAccess Example
  • Example#5203 - Quickhash Iterator Example
  • Example#5204 - Quickhash String Values Example
  • Example#5205 - QuickHashIntSet::add example
  • Example#5206 - QuickHashIntSet::__construct example
  • Example#5207 - QuickHashIntSet::delete example
  • Example#5208 - QuickHashIntSet::exists example
  • Example#5209 - QuickHashIntSet::getSize example
  • Example#5210 - QuickHashIntSet::loadFromFile example
  • Example#5211 - QuickHashIntSet::loadFromString example
  • Example#5212 - QuickHashIntSet::saveToFile example
  • Example#5213 - QuickHashIntSet::saveToString example
  • Example#5214 - QuickHashIntHash::add example
  • Example#5215 - QuickHashIntHash::__construct example
  • Example#5216 - QuickHashIntHash::delete example
  • Example#5217 - QuickHashIntHash::exists example
  • Example#5218 - QuickHashIntHash::get example
  • Example#5219 - QuickHashIntHash::getSize example
  • Example#5220 - QuickHash IntHash file format
  • Example#5221 - QuickHash IntHash file format
  • Example#5222 - QuickHashIntHash::loadFromFile example
  • Example#5223 - QuickHashIntHash::loadFromString example
  • Example#5224 - QuickHashIntHash::saveToFile example
  • Example#5225 - QuickHashIntHash::saveToString example
  • Example#5226 - QuickHashIntHash::set example
  • Example#5227 - QuickHashIntHash::update example
  • Example#5228 - QuickHashStringIntHash::add example
  • Example#5229 - QuickHashStringIntHash::__construct example
  • Example#5230 - QuickHashStringIntHash::delete example
  • Example#5231 - QuickHashStringIntHash::get example
  • Example#5232 - QuickHashStringIntHash::getSize example
  • Example#5233 - QuickHash StringIntHash file format
  • Example#5234 - QuickHash IntHash file format
  • Example#5235 - QuickHashStringIntHash::loadFromFile example
  • Example#5236 - QuickHashStringIntHash::loadFromString example
  • Example#5237 - QuickHashStringIntHash::saveToFile example
  • Example#5238 - QuickHashStringIntHash::saveToString example
  • Example#5239 - QuickHashStringIntHash::set example
  • Example#5240 - QuickHashStringIntHash::update example
  • Example#5241 - QuickHashIntStringHash::add example
  • Example#5242 - QuickHashIntStringHash::__construct example
  • Example#5243 - QuickHashIntStringHash::delete example
  • Example#5244 - QuickHashIntStringHash::get example
  • Example#5245 - QuickHashIntStringHash::getSize example
  • Example#5246 - QuickHash IntString file format
  • Example#5247 - QuickHash IntString file format
  • Example#5248 - QuickHashIntStringHash::loadFromFile example
  • Example#5249 - QuickHashIntStringHash::loadFromString example
  • Example#5250 - QuickHashIntStringHash::saveToFile example
  • Example#5251 - QuickHashIntStringHash::saveToString example
  • Example#5252 - QuickHashIntStringHash::set example
  • Example#5253 - QuickHashIntStringHash::update example
  • Example#5254 - Beispiele von Reflection in der Shell (dem Terminal)
  • Example#5255 - Extending the built-in classes
  • Example#5256 - Reflection::getModifierNames example
  • Example#5257 - Basic usage ReflectionClass
  • Example#5258 - Basic usage of ReflectionClass::export
  • Example#5259 - Basic usage
  • Example#5260 - Filtering results by class name
  • Example#5261 - Filtering results by class name, with inheritance
  • Example#5262 - Usage of ReflectionClass::getConstant
  • Example#5263 - Basic usage of ReflectionClass::getConstructor
  • Example#5264 - ReflectionClass::getDefaultProperties example
  • Example#5265 - ReflectionClass::getDocComment example
  • Example#5266 - ReflectionClass::getEndLine example
  • Example#5267 - Basic usage of ReflectionClass::getExtension
  • Example#5268 - Basic usage of ReflectionClass::getExtensionName
  • Example#5269 - ReflectionClass::getInterfaceNames example
  • Example#5270 - ReflectionClass::getInterfaces example
  • Example#5271 - Basic usage of ReflectionClass::getMethod
  • Example#5272 - Basic usage of ReflectionClass::getMethods
  • Example#5273 - Filtering results from ReflectionClass::getMethods
  • Example#5274 - ReflectionClass::getName example
  • Example#5275 - ReflectionClass::getNamespaceName example
  • Example#5276 - ReflectionClass::getProperties filtering example
  • Example#5277 - Basic usage of ReflectionClass::getProperty
  • Example#5278 - Basic ReflectionClass::getReflectionConstants example
  • Example#5279 - ReflectionClass::getShortName example
  • Example#5280 - Basic usage of ReflectionClass::getStaticPropertyValue
  • Example#5281 - ReflectionClass::hasConstant example
  • Example#5282 - ReflectionClass::hasMethod example
  • Example#5283 - ReflectionClass::hasProperty example
  • Example#5284 - ReflectionClass::inNamespace example
  • Example#5285 - ReflectionClass::isAbstract example
  • Example#5286 - ReflectionClass::isAnonymous example
  • Example#5287 - Basic usage of ReflectionClass::isCloneable
  • Example#5288 - ReflectionClass::isFinal example
  • Example#5289 - ReflectionClass::isInstance related examples
  • Example#5290 - ReflectionClass::isInstantiable example
  • Example#5291 - Basic usage of ReflectionClass::isInterface
  • Example#5292 - Basic usage of ReflectionClass::isInternal
  • Example#5293 - Basic ReflectionClass::isIterable Usage
  • Example#5294 - ReflectionClass::isReadOnly example
  • Example#5295 - Basic usage of ReflectionClass::newInstanceArgs
  • Example#5296 - ReflectionClass::__toString example
  • Example#5297 - Basic usage
  • Example#5298 - Filtering results by class name
  • Example#5299 - Filtering results by class name, with inheritance
  • Example#5300 - ReflectionClassConstant::isEnumCase example
  • Example#5301 - ReflectionEnum::getBackingType example
  • Example#5302 - ReflectionEnum::getCase example
  • Example#5303 - ReflectionEnum::getCases example
  • Example#5304 - ReflectionEnum::hasCase example
  • Example#5305 - ReflectionEnum::isBacked example
  • Example#5306 - ReflectionEnum::getValue example
  • Example#5307 - ReflectionEnum::getBackingValue example
  • Example#5308 - ReflectionExtension example
  • Example#5309 - ReflectionExtension::getClasses example
  • Example#5310 - ReflectionExtension::getClassNames example
  • Example#5311 - ReflectionExtension::getConstants example
  • Example#5312 - ReflectionExtension::getDependencies example
  • Example#5313 - ReflectionExtension::getFunctions example
  • Example#5314 - ReflectionExtension::getINIEntries example
  • Example#5315 - ReflectionExtension::getName example
  • Example#5316 - ReflectionExtension::getVersion example
  • Example#5317 - ReflectionExtension::info example
  • Example#5318 - ReflectionFunction::__construct example
  • Example#5319 - ReflectionFunction::invoke example
  • Example#5320 - ReflectionFunction::invokeArgs example
  • Example#5321 - ReflectionFunction::invokeArgs with references example
  • Example#5322 - ReflectionFunction::isAnonymous example
  • Example#5323 - ReflectionFunction::__toString example
  • Example#5324 - Basic usage with a class method
  • Example#5325 - Basic usage with a function
  • Example#5326 - Filtering results by class name
  • Example#5327 - Filtering results by class name, with inheritance
  • Example#5328 - ReflectionFunctionAbstract::getClosureUsedVariables example
  • Example#5329 - ReflectionFunctionAbstract::getReturnType example
  • Example#5330 - Usage on built-in functions
  • Example#5331 - ReflectionFunctionAbstract::getTentativeReturnType example
  • Example#5332 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5333 - Usage on built-in functions
  • Example#5334 - ReflectionFunctionAbstract::hasTentativeReturnType example
  • Example#5335 - ReflectionFunctionAbstract::isClosure example
  • Example#5336 - ReflectionFunctionAbstract::isDeprecated example
  • Example#5337 - ReflectionMethod::__construct example
  • Example#5338 - ReflectionMethod::createFromMethodName example
  • Example#5339 - ReflectionMethod::getDeclaringClass example
  • Example#5340 - ReflectionMethod::getModifiers example
  • Example#5341 - ReflectionMethod::getPrototype example
  • Example#5342 - ReflectionMethod::hasPrototype example
  • Example#5343 - ReflectionMethod::invoke example
  • Example#5344 - ReflectionMethod::invokeArgs example
  • Example#5345 - Simple Class definition
  • Example#5346 - ReflectionMethod::__toString example
  • Example#5347 - ReflectionNamedType::isBuiltin example
  • Example#5348 - Using the ReflectionParameter class
  • Example#5349 - Basic usage
  • Example#5350 - Filtering results by class name
  • Example#5351 - Filtering results by class name, with inheritance
  • Example#5352 - Using the ReflectionParameter class
  • Example#5353 - Getting the class that declared the method
  • Example#5354 - Getting default values of function parameters
  • Example#5355 - Getting default values' constant names of function parameters
  • Example#5356 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5357 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5358 - ReflectionParameter::getType Usage in PHP 8.0.0 and later
  • Example#5359 - ReflectionParameter::hasType example
  • Example#5360 - PHP 8.0.0 equivalent
  • Example#5361 - PHP 8.0.0 equivalent
  • Example#5362 - ReflectionParameter::__toString example
  • Example#5363 - ReflectionProperty::__construct example
  • Example#5364 - Getting value from private and protected properties using ReflectionProperty class
  • Example#5365 - Basic usage
  • Example#5366 - Filtering results by class name
  • Example#5367 - Filtering results by class name, with inheritance
  • Example#5368 - ReflectionProperty::getDefaultValue example
  • Example#5369 - ReflectionProperty::getDocComment example
  • Example#5370 - Multiple property declarations
  • Example#5371 - ReflectionProperty::getType example
  • Example#5372 - ReflectionProperty::getValue example
  • Example#5373 - ReflectionProperty::hasDefaultValue example
  • Example#5374 - ReflectionProperty::hasType example
  • Example#5375 - ReflectionProperty::isDefault example
  • Example#5376 - ReflectionProperty::isInitialized example
  • Example#5377 - ReflectionProperty::isPromoted example
  • Example#5378 - Simple Class definition
  • Example#5379 - ReflectionProperty::setValue example
  • Example#5380 - ReflectionType::allowsNull example
  • Example#5381 - ReflectionType::__toString example
  • Example#5382 - ReflectionUnionType::getTypes example
  • Example#5383 - ReflectionGenerator::__construct example
  • Example#5384 - ReflectionGenerator::getExecutingFile example
  • Example#5385 - ReflectionGenerator::getExecutingGenerator example
  • Example#5386 - ReflectionGenerator::getExecutingLine example
  • Example#5387 - ReflectionGenerator::getFunction example
  • Example#5388 - ReflectionGenerator::getThis example
  • Example#5389 - ReflectionGenerator::getTrace example
  • Example#5390 - ReflectionIntersectionType::getTypes example
  • Example#5391 - Basic ReflectionReference::getId usage
  • Example#5392 - boolval examples
  • Example#5393 - debug_zval_dump example
  • Example#5394 -
  • Example#5395 - Ein einfacher Vergleich von empty / isset
  • Example#5396 - empty und Zeichenketten-Offsets
  • Example#5397 - floatval-Beispiel
  • Example#5398 - floatval nichtnumerische Anfangszeichen Beispiel
  • Example#5399 - get_debug_type example
  • Example#5400 - get_defined_vars-Beispiel
  • Example#5401 - get_resource_id produces the same result as an int cast
  • Example#5402 - get_resource_type-Beispiel
  • Example#5403 - gettype-Beispiel
  • Example#5404 - intval-Beispiele
  • Example#5405 - Überprüfen, ob die Variable ein Array ist
  • Example#5406 - is_bool-Beispiele
  • Example#5407 - is_callable-Beispiel
  • Example#5408 - is_callable und Konstruktoren
  • Example#5409 - is_countable examples
  • Example#5410 - is_float-Beispiel
  • Example#5411 - is_int-Beispiel
  • Example#5412 - is_iterable examples
  • Example#5413 - is_null-Beispiel
  • Example#5414 - is_numeric-Beispiele
  • Example#5415 - is_numeric mit Leerzeichen
  • Example#5416 - is_object-Beispiel
  • Example#5417 - is_resource-Beispiel
  • Example#5418 - is_scalar-Beispiel
  • Example#5419 - is_string-Beispiel
  • Example#5420 - isset-Beispiele
  • Example#5421 - isset und Zeichenketten-Offsets
  • Example#5422 - print_r-Beispiel
  • Example#5423 - return-Parameter-Beispiel
  • Example#5424 - serialize-Beispiel
  • Example#5425 - settype-Beispiel
  • Example#5426 - strval-Beispiel für die Verwendung der magischen __toString-Methode
  • Example#5427 - unserialize-Beispiel
  • Example#5428 - unserialize_callback_func-Beispiel
  • Example#5429 - unset-Beispiel
  • Example#5430 - Verwendung von (unset) Casting
  • Example#5431 - var_dump-Beispiel
  • Example#5432 - var_export-Beispiele
  • Example#5433 - Export von stdClass (seit PHP 7.3.0)
  • Example#5434 - Export von Klassen
  • Example#5435 - Nutzung von __set_state
  • Example#5436 -
  • Example#5437 - OAuth::fetch example
  • Example#5438 - OAuth::getAccessToken example
  • Example#5439 - OAuth::getRequestToken example
  • Example#5440 - OAuth::setRequestEngine example
  • Example#5441 - An OAuth::setRsaCertificate example
  • Example#5442 - OAuth::setToken example
  • Example#5443 - OAuthProvider::__construct example
  • Example#5444 - Example OAuthProvider::consumerHandler callback
  • Example#5445 - OAuthProvider::generateToken example
  • Example#5446 - OAuthProvider::is2LeggedEndpoint example
  • Example#5447 - Example OAuthProvider::timestampNonceHandler callback
  • Example#5448 - Example OAuthProvider::tokenHandler callback
  • Example#5449 - is_soap_fault-Beispiel
  • Example#5450 - Die SOAP-Standardmethode zur Fehlerbehandlung ist das Werfen von Exceptions.
  • Example#5451 - Die Verwendung von TLS 1.3 vorschreiben
  • Example#5452 - SoapClient::__construct-Beispiel
  • Example#5453 - Verwendung des Features SOAP_SINGLE_ELEMENT_ARRAYS
  • Example#5454 - SoapClient::__doRequest-Beispiel
  • Example#5455 - SoapClient::__getFunctions-Beispiel
  • Example#5456 - SoapClient::__getLastRequest()-Beispiel
  • Example#5457 - SoapClient::__getLastRequestHeaders()-Beispiel
  • Example#5458 - SoapClient::__getLastResponse()-Beispiel
  • Example#5459 - SoapClient::__getLastResponse()-Beispiel
  • Example#5460 - SoapClient::__getTypes-Beispiel
  • Example#5461 - SoapClient::__setLocation-Beispiel
  • Example#5462 - SoapClient::__setSoapHeaders-Beispiel
  • Example#5463 - Mehrere Header setzen
  • Example#5464 - SoapClient::__soapCall-Beispiel
  • Example#5465 - SoapServer::addFunction-Beispiel
  • Example#5466 - SoapServer::__construct-Beispiel
  • Example#5467 - SoapServer::getFunctions-Beispiel
  • Example#5468 - SoapServer::handle-Beispiel
  • Example#5469 - SoapServer::setPersistence-Beispiel
  • Example#5470 - Beispiel 1
  • Example#5471 - Beispiel 2
  • Example#5472 - SoapHeader::__construct-Beispiel
  • Example#5473 - SoapParam::__construct-Beispiel
  • Example#5474 - SoapVar::__construct-Beispiel
  • Example#5475 - Yar Server Example
  • Example#5476 - Access the server in borwser(GET request)
  • Example#5477 - Yar Client Example
  • Example#5478 - Yar Concurrent Client Example
  • Example#5479 - Yar_Server::__construct example
  • Example#5480 - Yar_Server::handle example
  • Example#5481 - Yar_Client::__call example
  • Example#5482 - Yar_Client::__construct example
  • Example#5483 - Yar_Client::setOpt example
  • Example#5484 - Yar_Concurrent_Client::call example
  • Example#5485 - Yar_Concurrent_Client::loop example
  • Example#5486 - Yar_Concurrent_Client::reset example
  • Example#5487 - Yar_Server_Exception::getType example
  • Example#5488 - Yar_Client_Exception::getType example
  • Example#5489 - XMLRPC client functions example
  • Example#5490 - XML-RPC type example
  • Example#5491 - A xmlrpc_set_type example
  • Example#5492 - For Each in ASP
  • Example#5493 - foreach in PHP
  • Example#5494 - com-Beispiel 1
  • Example#5495 - com-Beispiel 2
  • Example#5496 - dotnet example
  • Example#5497 - variant-Beispiel
  • Example#5498 - Basic COMPersistHelper::saveToFile Usage
  • Example#5499 - COM event sink example
  • Example#5500 - Registering a PHP script to run as a service
  • Example#5501 - Unregistering a service
  • Example#5502 - Running as a service
  • Example#5503 - A win32_create_service example
  • Example#5504 - A win32_create_service example with dependencies
  • Example#5505 - A win32_create_service example with recovery
  • Example#5506 - A win32_delete_service example
  • Example#5507 - A win32_start_service_ctrl_dispatcher example
  • Example#5508 - book.xml
  • Example#5509 - Creating a new DOMAttr object
  • Example#5510 - DOMAttr::isId() Example
  • Example#5511 - Creating a new DOMCdataSection object
  • Example#5512 - DOMCharacterData::after example
  • Example#5513 - DOMCharacterData::before example
  • Example#5514 - DOMCharacterData::remove example
  • Example#5515 - DOMCharacterData::replaceWith example
  • Example#5516 - Creating a new DOMComment
  • Example#5517 - DOMDocument::adoptNode example
  • Example#5518 - DOMDocument::append example
  • Example#5519 - Creating a new DOMDocument
  • Example#5520 - Creating a new element and inserting it as root
  • Example#5521 - Passing text containing an unescaped & as value
  • Example#5522 - Creating a new element and inserting it as root
  • Example#5523 - A namespace prefix example
  • Example#5524 - DOMDocument::getElementById() Example
  • Example#5525 - Basic Usage Example
  • Example#5526 - Get all the XInclude elements
  • Example#5527 - DOMDocument::importNode example
  • Example#5528 - Creating a Document
  • Example#5529 - Creating a Document
  • Example#5530 - Creating a Document
  • Example#5531 - Creating a Document
  • Example#5532 - DOMDocument::prepend example
  • Example#5533 - Adding a new method to DOMElement to ease our code
  • Example#5534 - Retrieving elements as custom class
  • Example#5535 - Retrieving owner document
  • Example#5536 - Custom objects are transient
  • Example#5537 - DOMDocument::replaceChildren example
  • Example#5538 - Saving a DOM tree into a file
  • Example#5539 - Saving a HTML tree into a string
  • Example#5540 - Saving a HTML tree into a file
  • Example#5541 - Saving a DOM tree into a string
  • Example#5542 - Example of DTD validation
  • Example#5543 - DOMDocument::xinclude() example
  • Example#5544 - DOMDocumentFragment::append example
  • Example#5545 - Appending XML data to your document
  • Example#5546 - DOMDocumentFragment::prepend example
  • Example#5547 - DOMDocumentFragment::replaceChildren example
  • Example#5548 - DOMElement::after example
  • Example#5549 - DOMElement::append example
  • Example#5550 - DOMElement::before example
  • Example#5551 - Creating a new DOMElement
  • Example#5552 - DOMElement::getAttributeNames example
  • Example#5553 - DOMElement::insertAdjacentElement example
  • Example#5554 - DOMElement::insertAdjacentText example
  • Example#5555 - DOMElement::prepend example
  • Example#5556 - DOMElement::remove example
  • Example#5557 - DOMElement::replaceChildren example
  • Example#5558 - DOMElement::replaceWith example
  • Example#5559 - Setting an attribute
  • Example#5560 - DOMElement::toggleAttribute example
  • Example#5561 - Creating a new DOMEntityReference
  • Example#5562 - Creating a document with an attached DTD
  • Example#5563 - Testing your DOM Implementation
  • Example#5564 - Adding a child
  • Example#5565 - Nested children
  • Example#5566 - DOMNode::contains example
  • Example#5567 - DOMNode::getLineNo example
  • Example#5568 - DOMNode::getNodePath example
  • Example#5569 - DOMNode::getRootNode example
  • Example#5570 - DOMNode::isEqualNode example
  • Example#5571 - Removing a child
  • Example#5572 - Traversing all the entries of the table
  • Example#5573 - DOMParentNode::replaceChildren example
  • Example#5574 - Creating a new DOMProcessingInstruction object
  • Example#5575 - Creating a new DOMText
  • Example#5576 - Getting the count of all the english books
  • Example#5577 - Getting all the english books
  • Example#5578 - book.xml
  • Example#5579 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#5580 - DOMXPath::registerPHPFunctions with php:function
  • Example#5581 - Importiert SimpleXML in DOM mit der Funktion dom_import_simplexml
  • Example#5582 - A libxml_get_errors example
  • Example#5583 - libxml_set_external_entity_loader example
  • Example#5584 - A libxml_set_streams_context example
  • Example#5585 - A libxml_use_internal_errors example
  • Example#5586 - Einzubindende Datei example.php mit XML-String
  • Example#5587 - <plot> ermitteln
  • Example#5588 - Auf <line> zugreifen
  • Example#5589 - Auf nicht-eindeutige Elemente per SimpleXML zugreifen
  • Example#5590 - Attribute verwenden
  • Example#5591 - Vergleichen von Elementen und Attributen mit Text
  • Example#5592 - Zwei Elemente vergleichen
  • Example#5593 - XPath verwenden
  • Example#5594 - Werte setzen
  • Example#5595 - Elemente und Attribute hinzufügen
  • Example#5596 - DOM-Interoperabilität
  • Example#5597 - Laden eines defekten XML-Strings
  • Example#5598 - Hinzufügen von Attributen und Kindern zu einem SimpleXML-Element
  • Example#5599 - Hinzufügen von Attributen und Kindern zu einem SimpleXML-Element
  • Example#5600 - XML erstellen
  • Example#5601 - Anwendung von asXML() auf SimpleXMLElement::xpath-Ergebnisse
  • Example#5602 - Einen XML-String auswerten
  • Example#5603 - Ein children()-Pseudo-Array durchlaufen
  • Example#5604 - Arbeiten mit Namensräumen
  • Example#5605 - Erstellen eines SimpleXMLElement-Objekts
  • Example#5606 - Erstellen eines SimpleXMLElement-Objekts von einer URL
  • Example#5607 - Counting the number of children
  • Example#5608 - Return the current element
  • Example#5609 - Ermitteln der Dokument-Namensräume
  • Example#5610 - Arbeiten mit mehreren Namensräumen
  • Example#5611 - Ermitteln des XML-Element-Namens
  • Example#5612 - Verwendete Dokument-Namespaces zurückgeben
  • Example#5613 - Return the sub-elements of the current element
  • Example#5614 - Check whether the current element has sub-elements
  • Example#5615 - Get the current XML tag key
  • Example#5616 - Move to the next element
  • Example#5617 - Einen Namespace-Prefix zur Verwendung in einem XPath-Query setzen
  • Example#5618 - Rewind to the first element
  • Example#5619 - Get string content
  • Example#5620 - Check whether the current element is valid
  • Example#5621 - Xpath
  • Example#5622 - DOM-Import
  • Example#5623 - Ein XML-Dokument auswerten
  • Example#5624 - Einen XML-String auswerten
  • Example#5625 - Serializing a single value with WDDX
  • Example#5626 - Using incremental packets with WDDX
  • Example#5627 - wddx_serialize_vars-Beispiel
  • Example#5628 - Show XML Element Structure
  • Example#5629 - Map XML to HTML
  • Example#5630 - External Entity Example
  • Example#5631 - xmltest.xml
  • Example#5632 - xmltest2.xml
  • Example#5633 - xml_parse_into_struct example
  • Example#5634 - moldb.xml - small database of molecular information
  • Example#5635 - parsemoldb.php - parses moldb.xml into an array of molecular objects
  • Example#5636 - Chunked parsing of large XML documents
  • Example#5637 - xml_set_object example
  • Example#5638 - Validierung von XML
  • Example#5639 - Creating a simple XML document
  • Example#5640 - Working with XML namespaces
  • Example#5641 - Working with the OO API
  • Example#5642 - Direkte Ausgabe von XML
  • Example#5643 - XMLWriter::setIndent und gemischter Inhalt
  • Example#5644 - Grundsätzliche XMLWriter::startAttribute Verwendung
  • Example#5645 - Mischen von Kindelementen und Attributen
  • Example#5646 - Grundsätzliche xmlwriter_write_cdata Verwendung
  • Example#5647 - collection.xml
  • Example#5648 - collection.xsl
  • Example#5649 - fruits.xml
  • Example#5650 - fruits.xsl
  • Example#5651 - Sammel und ausgaben der Fehler
  • Example#5652 - Verwendung von XSLTProcessor
  • Example#5653 - Prüfen auf EXSLT-Unterstützung
  • Example#5654 - Einfacher Aufruf einer PHP-Funktion durch ein Stylesheet
  • Example#5655 - Ändern des Parameters "owner" vor der Transformation
  • Example#5656 - Ausgabe des Profilers
  • Example#5657 - Transformation in ein DOMDocument
  • Example#5658 - Transformation in eine HTML-Datei
  • Example#5659 - Transformation in einen String
  • Example#5660 - Ein verstecktes HTML-Formularelement
  • Example#5661 - Daten, die vom Benutzer bearbeitet werden sollen
  • Example#5662 - In einem URL
  • Example#5663 - JavaScript mit PHP generieren
  • Example#5664 - PHP/FI Code-Beispiel
  • Example#5665 - Aktiviere volle Fehlerausgaben im Browser für die dev. Domain
  • Example#5666 - Binde für ein zu sicherndes Verzeichnis ein Sicherheitsscript hinzu
  • Example#5667 - include_path unter Unix
  • Example#5668 - include_path unter Windows
  • Example#5669 - include_path unter Unix unter Verwendung der ${USER}-Umgebungsvariablen
  • Example#5670 - string.rot13
  • Example#5671 - string.toupper
  • Example#5672 - string.tolower
  • Example#5673 - string.strip_tags
  • Example#5674 - convert.base64-encode & convert.base64-decode
  • Example#5675 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5676 - convert.iconv.*
  • Example#5677 - zlib.deflate und zlib.inflate
  • Example#5678 - Vereinfachte Verwendung von zlib.deflate
  • Example#5679 - bzip2.compress und bzip2.decompress
  • Example#5680 - Ver- und Entschlüsselung mit Blowfish
  • Example#5681 - Verschlüsseln einer Datei mit AES-128 CBC und SHA256 HMAC

User Contributed Notes

There are no user contributed notes for this page.


Changelog

Folgende Änderungen wurden an den Funktionen der gebündelten Extensions vorgenommen.

Version Function Beschreibung

User Contributed Notes

There are no user contributed notes for this page.


Windows HTML-Hilfe

  • Über diese Ausgabe
  • 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.


Über diese Ausgabe

Die Version des Handbuchs im Windows-HTML-Hilfe-Format wendet sich an Entwickler, die das Handbuch inklusive der Kommentare immer griffbreit haben wollen und trotzdem nicht auf das Laden einer Webseite warten wollen. Diese Ausgabe bietet den kompletten Inhalt des Handbuchs, ergänzt um die Nutzer-Kommentare sowie einige nützliche Features, die das Anzeigeprogramm zur Verfügung stellt. Nur Erstellung nutzen wir Skripte, außerdem binden wir verschiedene "Skins" ein.

Diese Distribution des PHP Handbuchs enthält viele Dateien, unter anderem die Hauptdatei php_manual_de.chm. Um diese anzusehen, doppelklicken Sie darauf (vermutlich haben Sie das schon). Eventuell sehen Sie auch eine Datei php_manual_de.chw in diesem Verzeichnis. Diese Datei wird angelegt, wenn Sie das erste Mal den Index-Reiter öffnen; sie enthält einen Index der Handbuchseiten.

Für alle, die an den technischen Details der Microsoft-HTML-Hilfe interessiert sind, ist » http://www.helpware.net/ eine gute Quelle. Weitere Informationen und den Stand der Windows-HTML-Hilfe in den Microsoft-Hilfe-Formaten in der Vergangenheit finden Sie in einem » WinWriters-Artikel.

User Contributed Notes

There are no user contributed notes for this page.


Using PHP Manual CHM Edition

Inhaltsverzeichnis

  • 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

Inhaltsverzeichnis

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

Hinweis:

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.

Hinweis:

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

Hinweis:

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

Hinweis:

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.

Hinweis:

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.