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.

Description

public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool

Validates a document based on the given schema file.

Parameters

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.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool

Validates a document based on a schema defined in the given string.

Parameters

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.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

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.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure. If the document has no DTD attached, this method will return false.

Examples

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

See Also

  • 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

Description

public DOMDocument::xinclude(int $options = 0): int|false

This method substitutes » XIncludes in a DOMDocument object.

Note:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parameters

options

Bitwise OR of the libxml option constants.

Return Values

Returns the number of XIncludes in the document, -1 if some processing failed, or false if there were no substitutions.

Examples

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

?>

The above example will output something similar to:

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

Class synopsis

class DOMDocumentFragment extends DOMNode implements DOMParentNode {
/* Properties */
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Inherited properties */
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;
/* Methods */
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
/* Inherited methods */
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
}

Properties

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

Changelog

Version | Description
8.0.0 | The firstElementChild, lastElementChild, and childElementCount properties have been added.
8.0.0 | DOMDocumentFragment implements DOMParentNode now.

Table of Contents

  • 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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

<hello/>beautiful<world/>

See Also

  • 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

Description

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.

Parameters

data

XML to append.

Return Values

Returns true on success or false on failure.

Examples

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

The above example will output:

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

Description

public DOMDocumentFragment::__construct()

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

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

DOMDocumentFragment::prepend

(PHP 8)

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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

<hello/>beautiful<world/>

See Also

  • 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

Description

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

Replaces the children in the document fragment with new nodes.

Parameters

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

beautiful
<world/>

See Also

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

Introduction

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

Class synopsis

class DOMDocumentType extends DOMNode {
/* Properties */
public readonly string $name;
public readonly DOMNamedNodeMap $entities;
public readonly DOMNamedNodeMap $notations;
public readonly string $publicId;
public readonly string $systemId;
public readonly ?string $internalSubset;
/* Inherited properties */
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;
/* Inherited methods */
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
}

Properties

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This does not contain the delimiting square brackets.

User Contributed Notes

There are no user contributed notes for this page.


The DOMElement class

(PHP 5, PHP 7, PHP 8)

Class synopsis

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* Properties */
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;
/* Inherited properties */
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;
/* Methods */
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
/* Inherited methods */
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
}

Properties

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

schemaTypeInfo

Not implemented yet, always return null

tagName

The element name

className

A string representing the classes of the element separated by spaces

id

The element ID

Changelog

Version | Description
8.0.0 | The firstElementChild, lastElementChild, childElementCount, previousElementSibling, and nextElementSibling properties have been added.
8.0.0 | DOMElement implements DOMParentNode and DOMChildNode now.

Notes

Note:

The DOM extension uses UTF-8 encoding. Use mb_convert_encoding(), UConverter::transcode(), or iconv() to handle other encodings.

Table of Contents

  • 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

Description

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

Adds the passed nodes after the element.

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
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. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

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

See Also

  • 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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

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

See Also

  • 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

Description

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

Adds the passed nodes before the element.

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
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. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

hello
<beautiful/>
<world/>

See Also

  • 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

Description

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.

Parameters

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.

Examples

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

?>

See Also

  • 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

Description

public DOMElement::getAttribute(string $qualifiedName): string

Gets the value of the attribute with name qualifiedName for the current node.

Parameters

qualifiedName

The name of the attribute.

Return Values

The value of the attribute, or an empty string if no attribute with the given qualifiedName is found.

See Also

  • 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

Description

public DOMElement::getAttributeNames(): array

Get attribute names.

Parameters

This function has no parameters.

Return Values

Return attribute names.

Examples

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

The above example will output:

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

Description

public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false

Returns the attribute node with name qualifiedName for the current element.

Parameters

qualifiedName

The name of the attribute.

Return Values

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

See Also

  • 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

Description

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.

Parameters

namespace

The namespace URI.

localName

The local name.

Return Values

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

See Also

  • 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

Description

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.

Parameters

namespace

The namespace URI.

localName

The local name.

Return Values

The value of the attribute, or an empty string if no attribute with the given localName and namespace is found.

See Also

  • 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

Description

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.

Parameters

qualifiedName

The tag name. Use * to return all elements within the element tree.

Return Values

This function returns a new instance of the class DOMNodeList of all matched elements.

See Also

  • 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

Description

public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

This function fetch all the descendant elements with a given localName and namespace.

Parameters

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.

Return Values

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 | Description
8.0.3 | namespace is nullable now.

See Also

  • 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

Description

public DOMElement::hasAttribute(string $qualifiedName): bool

Indicates whether attribute named qualifiedName exists as a member of the element.

Parameters

qualifiedName

The attribute name.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

public DOMElement::hasAttributeNS(?string $namespace, string $localName): bool

Indicates whether attribute in namespace namespace named localName exists as a member of the element.

Parameters

namespace

The namespace URI.

localName

The local name.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

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

Inserts an element at a relative position given by where.

Parameters

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.

Return Values

Return DOMElement or null on failure.

Examples

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

The above example will output:

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

See Also

  • DOMElement::insertAdjacentText() - Insert adjacent text

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent text

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

DOMElement::insertAdjacentText

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentText — Insert adjacent text

Description

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

Inserts text at a relative position given by where.

Parameters

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.

Return Values

No value is returned.

Examples

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

The above example will output:

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

See Also

  • DOMElement::insertAdjacentElement() - Insert adjacent element

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

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

DOMElement::prepend

(PHP 8)

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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

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

See Also

  • 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

Description

public DOMElement::remove(): void

Removes the element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

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

The above example will output:

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

See Also

  • 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

Description

public DOMElement::removeAttribute(string $qualifiedName): bool

Removes attribute named qualifiedName from the element.

Parameters

qualifiedName

The name of the attribute.

Return Values

Returns true on success or false on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • 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

Description

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Removes attribute attr from the element.

Parameters

attr

The attribute node.

Return Values

Returns true on success or false on failure.

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

See Also

  • 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

Description

public DOMElement::removeAttributeNS(?string $namespace, string $localName): void

Removes attribute localName in namespace namespace from the element.

Parameters

namespace

The namespace URI.

localName

The local name.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • 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

Description

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

Replaces the children in the element with new nodes.

Parameters

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

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

See Also

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

User Contributed Notes

There are no user contributed notes for this page.


Replaces the element with new nodes

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

DOMElement::replaceWith

(PHP 8)

DOMElement::replaceWith — Replaces the element with new nodes

Description

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

Replaces the element with new nodes.

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
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. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

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

See Also

  • 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

Description

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.

Parameters

qualifiedName

The name of the attribute.

value

The value of the attribute.

Return Values

The created or modified DOMAttr or false if an error occurred.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Examples

Example #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

See Also

  • 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

Description

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.

Parameters

attr

The attribute node.

Return Values

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.

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

See Also

  • 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

Description

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.

Parameters

attr

The attribute node.

Return Values

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.

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

See Also

  • 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

Description

public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void

Sets an attribute with namespace namespace and name name to the given value. If the attribute does not exist, it will be created.

Parameters

namespace

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Return Values

No value is returned.

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

See Also

  • 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

Description

public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void

Declares the attribute qualifiedName to be of type ID.

Parameters

qualifiedName

The name of the attribute.

isId

Set it to true if you want qualifiedName to be of type ID, false otherwise.

Return Values

No value is returned.

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

See Also

  • 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

Description

public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void

Declares the attribute specified by attr to be of type ID.

Parameters

attr

The attribute node.

isId

Set it to true if you want name to be of type ID, false otherwise.

Return Values

No value is returned.

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

See Also

  • 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

Description

public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void

Declares the attribute specified by qualifiedName and namespace to be of type ID.

Parameters

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.

Return Values

No value is returned.

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

See Also

  • 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

Description

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

Toggle the attribute.

Parameters

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.

Return Values

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

Examples

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

The above example will output:

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)

Introduction

This interface represents a known entity, either parsed or unparsed, in an XML document.

Class synopsis

class DOMEntity extends DOMNode {
/* Properties */
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;
/* Inherited properties */
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;
/* Inherited methods */
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
}

Properties

publicId

The public identifier associated with the entity if specified, and null otherwise.

systemId

The system identifier associated with the entity if specified, and null otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is null if it is an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is null otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is null otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntityReference class

(PHP 5, PHP 7, PHP 8)

Class synopsis

class DOMEntityReference extends DOMNode {
/* Inherited properties */
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;
/* Methods */
public __construct(string $name)
/* Inherited methods */
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
}

Table of Contents

  • 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

Description

public DOMEntityReference::__construct(string $name)

Creates a new DOMEntityReference object.

Parameters

name

The name of the entity reference.

Examples

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

?>

See Also

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


The DOMException class

(PHP 5, PHP 7, PHP 8)

Introduction

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Exceptions.

Class synopsis

final class DOMException extends Exception {
/* Properties */
public int $code;
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
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
}

Properties

code

An integer indicating the type of error generated

User Contributed Notes

There are no user contributed notes for this page.


The DOMImplementation class

(PHP 5, PHP 7, PHP 8)

Introduction

The DOMImplementation class provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Class synopsis

class DOMImplementation {
/* Methods */
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
}

Table of Contents

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

User Contributed Notes

LANGE.LUDO 07-Nov-2014 06:05
Ok got it working like a charm using "proxy pattern" with traits. The idea being declaring the common methods inside a "trait" in order for extended and registered Node Classes to have access even if not derived / child of the extended DOMNode…

Here a small snippet :
<?php
    namespace my;

    trait tNode
    {    // We need the magic method __get in order to add properties such as DOMNode->parentElement
        public function __get($name)
        {    if(property_exists($this, $name)){return $this->$name;}
            if(method_exists($this, $name)){return $this->$name();}
            throw new \ErrorException('my\\Node property \''.(string) $name.'\' not found…', 42, E_USER_WARNING);
        }

        // parentElement property definition
        private function parentElement()
        {    if($this->parentNode === null){return null;}
            if($this->parentNode->nodeType === XML_ELEMENT_NODE){return $this->parentNode;}
            return $this->parentNode->parentElement();
        }

        // JavaScript equivalent
        public function isEqualNode(\DOMNode $node){return $this->isSameNode($node);}
        public function compareDocumentPosition(\DOMNode $otherNode)
        {    if($this->ownerDocument !== $otherNode->ownerDocument){return DOCUMENT_POSITION_DISCONNECTED;}
            $c = strcmp($this->getNodePath(), $otherNode->getNodePath());
            if($c === 0){return 0;}
            else if($c < 0){return DOCUMENT_POSITION_FOLLOWING | ($c < -1 ? DOCUMENT_POSITION_CONTAINED_BY : 0);}
            return DOCUMENT_POSITION_PRECEDING | ($c > 1 ? DOCUMENT_POSITION_CONTAINS : 0);
        }
        public function contains(\DOMNode $otherNode){return ($this->compareDocumentPosition($otherNode) >= DOCUMENT_POSITION_CONTAINED_BY);}
    }

    class Document extends \DomDocument
    {    public function __construct($version=null, $encoding=null)
        {    parent::__construct($version, $encoding);
            $this->registerNodeClass('DOMNode', 'my\Node');
            $this->registerNodeClass('DOMElement', 'my\Element');
            $this->registerNodeClass('DOMDocument', 'my\Document');
            /* [...] */
        }
    }

    class Element extends \DOMElement
    {    use tNode;
        /* [...] */
    }

    class Node extends \DOMNode
    {    use tNode;
        /* [...] */
    }

?>
LANGE.LUDO 07-Nov-2014 08:14
From what I've seen you must "recode" the "createDocument" method in order to call your own object extension…

<?php
[...]
    public function createDocument($namespaceURI=null, $qualifiedName=null, DOMDocumentType $docType=null)
    {    $doc=new Document();
        $doc->appendChild(parent::createDocumentType('html'));
        $this->doc->appendChild($namespaceURI ? $this->doc->createElementNS($namespaceURI,$qualifiedName) : $this->doc->createElement($qualifiedName));
    return $doc;
    }
[...]
?>

Where I am struggling is extending the whole tree so that calling the customized Implementation method returns a whole extended tree…
Expected result : Implementation > Document > DOMDocument > Node > DOMNode
Actual result : Implementation > Document > DOMDocument > DOMNode :(
LANGE.LUDO 05-Nov-2014 10:59
Why not use the DOMImplementation to directly register your DOM Class extensions ?

<?php
namespace My;
class Implementation extends \DOMImplementation
{    private $doc;
    public function __construct(){return $this->createDocument();}
    public function __get($name){return $this->doc->{$name};}
    public function __set($name,$value){$this->doc->{$name}=$value;}
    public function __isset($name){return isset($this->doc->{$name});}
    public function __unset($name){return $this->doc->__unset($name);}
    public function __call($name,$args){return call_user_func_array(array($this->doc,$name),$args);}

    public function createDocument($namespaceURI=null,$qualifiedName=null,DOMDocumentType $docType=null)
    {    $this->doc=parent::createDocument($namespaceURI,$qualifiedName,$docType);
        $this->doc->xmlVersion='1.0';
        $this->doc->xmlEncoding='UTF-8';
        $this->doc->registerNodeClass('DOMDocument','My\Document');
        $this->doc->registerNodeClass('DOMDocumentFragment','My\DocumentFragment');
        $this->doc->registerNodeClass('DOMElement','My\Element');
        $this->doc->registerNodeClass('DOMComment','My\Comment');
        $this->doc->registerNodeClass('DOMNode','My\Node');
        /* …, …, … */
        return $this->doc;
    }
}
?>
giorgio dot liscio at email dot it 20-Jul-2010 06:26
officially, the w3 specifies that the way to access dom interfaces is through this class

so if you use

$doc = new DOMDocument("1.0", "UTF-8");

use instead:

$x = new DOMImplementation();
$doc = $x->createDocument(NULL,"rootElementName");
$doc->xmlVersion="1.0";
$doc->xmlEncoding="UTF-8";

it is not required by php's implementation, but, probably, it is a good practice

see:

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementation

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationList

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationSource


Creates a new DOMImplementation object

  • « DOMImplementation
  • DOMImplementation::createDocument »
  • PHP Manual
  • DOMImplementation
  • Creates a new DOMImplementation object

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creates a new DOMImplementation object

Description

DOMImplementation::__construct()

Creates a new DOMImplementation object.

Parameters

This function has no parameters.

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

Description

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.

Parameters

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.

Return Values

A new DOMDocument object or false on error. If namespace, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Errors/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 | Description
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.

See Also

  • 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=UTF-8" />
    <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

Description

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.

Parameters

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

A new DOMDocumentType node with its ownerDocument set to null or false on error.

Errors/Exceptions

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

Changelog

Version | Description
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Examples

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

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

See Also

  • 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

Description

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.

Parameters

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.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Examples

Example #1 Testing your DOM Implementation

<?php

$features = array(
'Core' => 'Core module',
'XML' => 'XML module',
'HTML' => 'HTML module',
'Views' => 'Views module',
'Stylesheets' => 'Style Sheets module',
'CSS' => 'CSS module',
'CSS2' => 'CSS2 module',
'Events' => 'Events module',
'UIEvents' => 'User interface Events module',
'MouseEvents' => 'Mouse Events module',
'MutationEvents' => 'Mutation Events module',
'HTMLEvents' => 'HTML Events module',
'Range' => 'Range module',
'Traversal' => 'Traversal module'
);

foreach ($features as $key => $name) {
if (DOMImplementation::hasFeature($key, '2.0')) {
echo "Has feature $name\n";
} else {
echo "Missing feature $name\n";
}
}

?>

See Also

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

Class synopsis

class DOMNamedNodeMap implements IteratorAggregate, Countable {
/* Properties */
public readonly int $length;
/* Methods */
public count(): int
public getIterator(): Iterator
public getNamedItem(string $qualifiedName): ?DOMNode
public getNamedItemNS(?string $namespace, string $localName): ?DOMNode
public item(int $index): ?DOMNode
}

Properties

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

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

Table of Contents

  • 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

Description

public DOMNamedNodeMap::count(): int

Gets the number of nodes in the map.

Parameters

This function has no parameters.

Return Values

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

Description

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

Parameters

This function has no parameters.

Return Values

An instance of an object implementing Iterator or Traversable

Errors/Exceptions

Throws an Exception on failure.

See Also

  • IteratorAggregate::getIterator() - Retrieve an external iterator

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

Description

public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode

Retrieves a node specified by its nodeName.

Parameters

qualifiedName

The nodeName of the node to retrieve.

Return Values

A node (of any type) with the specified nodeName, or null if no node is found.

See Also

  • 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

Description

public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode

Retrieves a node specified by localName and namespace.

Parameters

namespace

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Return Values

A node (of any type) with the specified local name and namespace URI, or null if no node is found.

See Also

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • « DOMNamedNodeMap::getNamedItemNS
  • DOMNode »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by index

DOMNamedNodeMap::item

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::item — Retrieves a node specified by index

Description

public DOMNamedNodeMap::item(int $index): ?DOMNode

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parameters

index

Index into this map.

Return Values

The node at the indexth position in the map, or null if that is not a valid index (greater than or equal to the number of nodes in this map).

User Contributed Notes

reyjacobs at yahoo dot com 07-Mar-2008 11:24
Nevermind: I got it, and here it is:

<?php
if($element->hasAttributes())
{
    $attributes = $element->attributes;
    if(!is_null($attributes))
    {
        foreach ($attributes as $index=>$attr)
        {
            echo $attr->name."=\"".$attr->value."\"";
        }
    }
}
?>


The DOMNode class

(PHP 5, PHP 7, PHP 8)

Class synopsis

class DOMNode {
/* Properties */
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;
/* Methods */
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
}

Properties

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

Notes

Note:

The DOM extension uses UTF-8 encoding. Use mb_convert_encoding(), UConverter::transcode(), or iconv() to handle other encodings.

See Also

  • » W3C specification of Node

Table of Contents

  • 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=utf-8"><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

Description

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.

Parameters

node

The appended child.

Return Values

The node added or false on error.

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

Examples

The following example will add a new element node to a fresh document.

Example #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Example #2 Nested children

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

See Also

  • 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

Description

public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false

Canonicalize nodes to a string

Parameters

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.

Return Values

Returns canonicalized nodes as a string or false on failure

See Also

  • 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

Description

public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false

Canonicalize nodes to a file.

Parameters

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.

Return Values

Number of bytes written or false on failure

See Also

  • 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

Description

public DOMNode::cloneNode(bool $deep = false): DOMNode|false

Creates a copy of the node.

Parameters

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to false.

Return Values

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

Description

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

Checks if node contains other node.

Parameters

other

Node to be checked.

Return Values

Returns true if node contains other node, false otherwise.

Examples

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

The above example will output:

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

Description

public DOMNode::getLineNo(): int

Gets line number for where the node is defined.

Parameters

This function has no parameters.

Return Values

Always returns the line number where the node was defined in.

Examples

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

The above example will output:

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

Description

public DOMNode::getNodePath(): ?string

Gets an XPath location path for the node.

Parameters

This function has no parameters.

Return Values

Returns a string containing the XPath, or null in case of an error.

Examples

Example #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";
}
?>

The above example will output:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

See Also

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.


Get root node

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

DOMNode::getRootNode

(PHP 8 >= 8.3.0)

DOMNode::getRootNode — Get root node

Description

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

Get root node.

Parameters

options

This parameter has no effect yet.

Return Values

Returns the root node.

Examples

Example #1 DOMNode::getRootNode() example

<?php

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

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

The above example will output:

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

Description

public DOMNode::hasAttributes(): bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

public DOMNode::hasChildNodes(): bool

This function checks if the node has children.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

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.

Parameters

node

The new node.

child

The reference node. If not supplied, node is appended to the children.

Return Values

The inserted node or false on error.

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

See Also

  • 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

Description

public DOMNode::isDefaultNamespace(string $namespace): bool

Tells whether namespace is the default namespace.

Parameters

namespace

The namespace URI to look for.

Return Values

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

Description

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

Checks that both nodes are equal.

Parameters

otherNode

The node.

Return Values

Returns true if both nodes are equal, false otherwise.

Examples

Example #1 DOMNode::isEqualNode() example

<?php

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

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

The above example will output:

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

Description

public DOMNode::isSameNode(DOMNode $otherNode): bool

This function indicates if two nodes are the same node. The comparison is not based on content

Parameters

otherNode

The compared node.

Return Values

Returns true on success or false on failure.

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

Description

public DOMNode::isSupported(string $feature, string $version): bool

Checks if the asked feature is supported for the specified version.

Parameters

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.

Return Values

Returns true on success or false on failure.

See Also

  • 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

Description

public DOMNode::lookupNamespaceURI(?string $prefix): ?string

Gets the namespace URI of the node based on the prefix.

Parameters

prefix

The prefix to look for. If this parameter is null, the method will return the default namespace URI, if any.

Return Values

Returns the associated namespace URI or null if none is found.

See Also

  • 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

Description

public DOMNode::lookupPrefix(string $namespace): ?string

Gets the namespace prefix of the node based on the namespace URI.

Parameters

namespace

The namespace URI.

Return Values

The prefix of the namespace or null on error.

See Also

  • 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

Description

public DOMNode::normalize(): void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

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

Description

public DOMNode::removeChild(DOMNode $child): DOMNode|false

This functions removes a child from a list of children.

Parameters

child

The removed child.

Return Values

If the child could be removed the function returns the old child or false on error.

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

Examples

The following example will delete the chapter element of our XML document.

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

The above example will output:

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

See Also

  • 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

Description

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.

Parameters

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.

Return Values

The old node or false if an error occur.

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

See Also

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

Class synopsis

class DOMNodeList implements IteratorAggregate, Countable {
/* Properties */
public readonly int $length;
/* Methods */
public count(): int
public getIterator(): Iterator
public item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null
}

Properties

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

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

See Also

  • » W3C specification of NodeList

Table of Contents

  • 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

Description

public DOMNodeList::count(): int

Gets the number of nodes in the list.

Parameters

This function has no parameters.

Return Values

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

Description

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

Parameters

This function has no parameters.

Return Values

An instance of an object implementing Iterator or Traversable

Errors/Exceptions

Throws an Exception on failure.

See Also

  • IteratorAggregate::getIterator() - Retrieve an external iterator

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

Description

public DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retrieves a node specified by index within the DOMNodeList object.

Tip

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parameters

index

Index of the node into the collection.

Return Values

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

Examples

Example #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";
}

?>

The above example will output:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

User Contributed Notes

jeffpuckett2 at gmail dot com 15-Jun-2016 02:55
DOMNodelist::item can return a DOMElement object, which extends DOMNode class. But it can also return a DOMText object.

<?php
$xml = '
<root>
  <node/>
  <node>
    <sub>more</sub>
  </node>
  <node>
    <sub>another</sub>
  </node>
  <node>value</node>
</root>
';

$doc = new DOMDocument();
$doc->loadXML($xml);

$items = $doc->documentElement->childNodes;
for ($i = 0; $i < $items->length; $i++)
  echo get_class($items->item($i)).PHP_EOL;
?>

Results in this output:

DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
Anonymous 25-Jun-2012 11:36
calling domnodelist->item($i) with an index $i greater than domnodelist->length - 1 , will return the entire document, will not produce an error, and will not circle back to the start of the list.
Nagy Attila 06-Jan-2011 09:02
DOMNodeList::item does not return in constant time!

If you need to iterate over large nodelist then you'd better use standard navigation.

Instead of:

<?php
foreach ($nodelist as $node) {
    // do something
}
?>

you could do:

<?php
$node = $parentnode->firstChild;

do {
    // do something
} while ($node = $node->nextSibling);
?>
olivier dot berger at it-sudparis dot eu 21-Aug-2008 02:56
It seems that with zend.ze1_compatibility_mode on, the only way to iterate over the items list is with :
for ($i = 0; $i < $nodeList->length; ++$i) {
    $nodeName = $nodeList->item($i)->nodeName;
    $nodeValue = $nodeList->item($i)->nodeValue;
}

As other attemps failed :

for ($i = 0; $i < $nodeList->length; ++$i) {
    $node = &$nodeList->item($i);
    $nodeName = $node->nodeName;
    $nodeValue = $node->nodeValue;
}

or :
foreach ($nodeList as $node) {
    echo $node->nodeName;
    echo $node->nodeValue;
}
vinyanov at poczta dot onet dot pl 05-Jan-2008 10:12
SimpleXML has its own SPL iterator. See http://www.php.net/~helly/php/ext/spl/classSimpleXMLIterator.html . But I guess that there are none for DOM nodes. By the way, two out of three implementations I found over the Net were not recursive, so I wrote my own. Here is the snippet:

<?php

class DOMNodeListIterator implements RecursiveIterator
{
    private
        $nodes,
        $offset;

    function __construct(DOMNodeList $nodes)
    {
        return $this -> nodes = $nodes;
    }

    function rewind()
    {
        return $this -> offset = 0;
    }

    function current()
    {
        return $this -> nodes -> item($this -> offset);
    }

    function key()
    {
        return $this -> current() -> nodeName;
    }

    function next()
    {
        return $this -> offset++;
    }

    function valid()
    {
        return $this -> offset < $this -> nodes -> length;
    }

    function hasChildren()
    {
        return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
    }

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

?>

Remember to use RecursiveIteratorIterator::SELF_FIRST flag when you create your iterator iterator.

<?php

$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

?>

Should work, has just few minutes though. :)
Hayley Watson 29-Oct-2007 02:14
Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist. In other words, a list of a parent node's children will change if you change the parent's children!
james dot dunmore at gmai dot com 27-Jul-2007 08:57
tfg_allardyce at gmail dot com

I have had exactly this problem.

To rectify I've had to do this:
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0);
$new_element = $doc->createElement('NewElement1');

$old_element_childNodes = $old_element->childNodes;
$length = $old_element_childNodes->length;

for($i = 0; $i < $length; $i++)
{
    $oldChildren_array[] = $old_element_childNodes->item($i);
}

foreach($oldChildren_array as $old_c)
{
    $new_element->appendChild($old_c);
}
?>

Rather than this:
(which I will bug report)
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0):
$new_element = $doc->createElement('NewElement1');

foreach($old_element->childNode as $node)
{
     $new_element->appendChild($node);
}

?>

Using the latter, randomally removes the children!
Geoffrey Thubron 26-May-2007 02:47
@ tfg_allardyce at gmail dot com

You could loop through the list backwards, that way, you are only ever taking off the last item from the list, and hence wont have disrupted the order.
oliver dot christen at camptocamp dot com 13-Feb-2007 07:27
NodeList are something annoying because you can't output the content with a simple print_r, so I did a little function that add all the node to a new empty DOMDocument and output it as a string.
Have fun.

<?php

public function domNodeList_to_string($DomNodeList) {
    $output = '';
    $doc = new DOMDocument;
    while ( $node = $DomNodeList->item($i) ) {
        // import node
        $domNode = $doc->importNode($node, true);
        // append node
        $doc->appendChild($domNode);
        $i++;
    }
    $output = $doc->saveXML();
    $output = print_r($output, 1);
    // I added this because xml output and ajax do not like each others
    $output = htmlspecialchars($output);
    return $output;
}

?>


The DOMNotation class

(PHP 5, PHP 7, PHP 8)

Class synopsis

class DOMNotation extends DOMNode {
/* Properties */
public readonly string $publicId;
public readonly string $systemId;
/* Inherited properties */
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;
/* Inherited methods */
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
}

Properties

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


The DOMParentNode interface

(PHP 8)

Interface synopsis

interface DOMParentNode {
/* Methods */
public append(DOMNode|string ...$nodes): void
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
}

Table of Contents

  • 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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

See Also

  • 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

Description

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

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

Parameters

nodes

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

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

See Also

  • 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

Description

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

Replace children in node.

Parameters

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Return Values

No value is returned.

Errors/Exceptions

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

Changelog

Version | Description
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

Examples

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

The above example will output:

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE HTML>
<html>foo<p/>bar</html>

User Contributed Notes

There are no user contributed notes for this page.


The DOMProcessingInstruction class

(PHP 5, PHP 7, PHP 8)

Class synopsis

class DOMProcessingInstruction extends DOMNode {
/* Properties */
public readonly string $target;
public string $data;
/* Inherited properties */
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;
/* Methods */
public __construct(string $name, string $value = "")
/* Inherited methods */
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
}

Properties

target

data

Table of Contents

  • 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

Description

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.

Parameters

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Examples

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

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

See Also

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

Introduction

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Class synopsis

class DOMText extends DOMCharacterData {
/* Properties */
public readonly string $wholeText;
/* Inherited properties */
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;
/* Methods */
public __construct(string $data = "")
public isElementContentWhitespace(): bool
public isWhitespaceInElementContent(): bool
public splitText(int $offset): DOMText|false
/* Inherited methods */
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
}

Properties

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Changelog

Version | Description
8.0.0 | The unimplemented method DOMText::replaceWholeText() has been removed.

Table of Contents

  • 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

Description

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

Creates a new DOMText object.

Parameters

data

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

Examples

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

?>

See Also

  • 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

Description

public DOMText::isElementContentWhitespace(): bool

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

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

Description

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.

Parameters

This function has no parameters.

Return Values

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

Description

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.

Parameters

offset

The offset at which to split, starting from 0.

Return Values

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


The DOMXPath class

(PHP 5, PHP 7, PHP 8)

Introduction

Supports XPath 1.0

Class synopsis

class DOMXPath {
/* Properties */
public readonly DOMDocument $document;
public bool $registerNodeNamespaces;
/* Methods */
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
}

Properties

document

registerNodeNamespaces

When set to true, namespaces in the node are registered.

Changelog

Version | Description
8.0.0 | The registerNodeNamespaces property has been added.

Table of Contents

  • 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

Description

public DOMXPath::__construct(DOMDocument $document, bool $registerNodeNS = true)

Creates a new DOMXPath object.

Parameters

document

The DOMDocument associated with the DOMXPath.

User Contributed Notes

thsoft at vipmail dot hu 04-Jul-2007 04:57
As of PHP 5.2.0, DOMXPath object implements XPath 1.0.
Saulo Vallory 26-Jun-2007 03:23
The DOMXPath object doesn't create a reference to the document. If you load a new xml using either load, loadXML or loadHTML functions the DOMXPath object will still query and evaluate over the source in the DOMDocument when it was created.


Evaluates the given XPath expression and returns a typed result if possible

  • « DOMXPath::__construct
  • DOMXPath::query »
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate

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

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

Description

public DOMXPath::evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression and returns a typed result if possible.

Parameters

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Return Values

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.

Examples

Example #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";

?>

The above example will output:

There are 2 english books

See Also

  • 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

Description

public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression.

Parameters

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Return Values

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.

Examples

Example #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";
}
?>

The above example will output:

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

See Also

  • 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

Description

public DOMXPath::registerNamespace(string $prefix, string $namespace): bool

Registers the namespace and prefix with the DOMXPath object.

Parameters

prefix

The prefix.

namespace

The URI of the namespace.

Return Values

Returns true on success or false on failure.

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 Functions »
  • 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

Description

public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void

This method enables the ability to use PHP functions within XPath expressions.

Parameters

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.

Return Values

No value is returned.

Examples

The following examples use book.xml which contains the following:

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

Example #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";
}

?>

The above example will output something similar to:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Example #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";
}

?>

The above example will output something similar to:

Books with multiple authors:
PHP Basics

See Also

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

Table of Contents

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

There are no user contributed notes for this page.


Gets a DOMElement object from a SimpleXMLElement object

  • « DOM Functions
  • libxml »
  • PHP Manual
  • DOM Functions
  • Gets a DOMElement object from a SimpleXMLElement object

dom_import_simplexml

(PHP 5, PHP 7, PHP 8)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

Description

dom_import_simplexml(object $node): DOMElement

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

Parameters

node

The SimpleXMLElement node.

Return Values

The DOMElement node added.

Changelog

Version | Description
8.0.0 | This function no longer returns null on failure.

Examples

Example #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

See Also

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node

User Contributed Notes

h4ss4n3 at hyj4z1 dot me 08-Sep-2020 08:08
//No need to initiate, import and append on example#1

(...)
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Erreur lors de la conversion du XML';
    exit;
}

//$dom = new DOMDocument('1.0');
//$dom_sxe = $dom->importNode($dom_sxe, true);
//$dom_sxe = $dom->appendChild($dom_sxe);

//use ownerDocument propertie
echo $dom->ownerDocument->saveXML();

?>
biniou at yopmail dot com 20-May-2016 09:58
Very useful to add a CDATA node with SimpleXMLElement (use it like addChild) :

<?php
class My_SimpleXMLElement extends SimpleXMLElement {

    public function addChildWithCData($name, $value = NULL) {
        $new_child = $this->addChild($name);

        $node = dom_import_simplexml($new_child);
        $no = $node->ownerDocument;
        $node->appendChild($no->createCDATASection($value));

        return $new_child;
    }
}
Jeff M 06-Mar-2009 01:09
SimpleXML is an 'Object Mapping XML API'. It is not DOM, per se. SimpleXML converts the XML elements into PHP's native data types.

The dom_import_simplexml and simplexml_import_dom functions do *not* create separate copies of the original object. You are free to use the methods of either or both interchangeably, since the underlying instance is the same.

<?php
    // initialize a simplexml object
    $sxe = simplexml_load_string('<root/>');

    // get a dom interface on the simplexml object
    $dom = dom_import_simplexml($sxe);

    // dom adds a new element under the root
    $element = $dom->appendChild(new DOMElement('dom_element'));

    // dom adds an attribute on the new element
    $element->setAttribute('creator', 'dom');

    // simplexml adds an attribute on the dom element
    $sxe->dom_element['sxe_attribute'] = 'added by simplexml';

    // simplexml adds a new element under the root
    $element = $sxe->addChild('sxe_element');

    // simplexml adds an attribute on the new element
    $element['creator'] = 'simplexml';

    // dom finds the simplexml element (via DOMNodeList->index)
    $element = $dom->getElementsByTagName('sxe_element')->item(0);

    // dom adds an attribute on the simplexml element
    $element->setAttribute('dom_attribute', 'added by dom');

    echo ('<pre>');
    print_r($sxe);
    echo ('</pre>');
?>

Outputs:

SimpleXMLElement Object
(
    [dom_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => dom
                    [sxe_attribute] => added by simplexml
                )

        )

    [sxe_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => simplexml
                    [dom_attribute] => added by dom
                )

        )

)

What this illustrates is that both interfaces are operating on the same underlying object instance. Also, when you dom_import_simplexml, you can create and add new elements without reference to an ownerDocument (or documentElement).

So passing a SimpleXMLElement to another method does not mean the recipient is limited to using SimpleXML methods.

Hey Presto! Your telescope has become a pair of binoculars!
crescentfreshpot at yahoo dot com 12-Dec-2007 12:22
justinpatrin at php dot net:
> To get a proper DOM document (which you need to do most things) you need...

No you don't. Just do:
<?php
$dom = dom_import_simplexml($xml)->ownerDocument;
?>
justinpatrin at php dot net 01-Jun-2006 09:44
I've found that newer versions of PHP5 require some special syntax in order to properly convert between SimpleXML and DOM. It's not as easy as calling dom_import_simplexml() with a SimpleXML node. To get a proper DOM document (which you need to do most things) you need:
<?php
//$xml is a SimpleXML instance
$domnode = dom_import_simplexml($xml);
$dom = new DOMDocument();
$domnode = $dom->importNode($domnode, true);
$dom->appendChild($domnode);
?>

Switching back, though, is, well...simple.

<?php
//$dom is a DOMDocument instance
$xml = simplexml_import_dom($dom);
?>


libxml

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation for PHP versions >= 7.4
    • Installation for PHP versions < 7.4
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • libXMLError — The libXMLError class
  • libxml Functions
    • 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.


Introduction

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

User Contributed Notes

There are no user contributed notes for this page.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation for PHP versions >= 7.4
  • Installation for PHP versions < 7.4
  • Runtime Configuration
  • Resource Types

User Contributed Notes

There are no user contributed notes for this page.


Requirements

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.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

LIBXML_BIGLINES (int)
Allows line numbers greater than 65535 to be reported correctly.

Note:

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.

Note:

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
Caution

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.

Note:

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.

Note:

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

Note:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (int)
Substitute entities
Caution

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

Note:

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.

Note:

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.

Note:

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

Note:

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)

Introduction

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Class synopsis

class libXMLError {
/* Properties */
public int $level;
public int $code;
public int $column;
public string $message;
public string $file;
public int $line;
}

Properties

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.

Note:

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 Functions

Table of Contents

  • 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 Functions
  • libxml_disable_entity_loader »
  • PHP Manual
  • libxml Functions
  • Clear libxml error buffer

libxml_clear_errors

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

libxml_clear_errors — Clear libxml error buffer

Description

libxml_clear_errors(): void

libxml_clear_errors() clears the libxml error buffer.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

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

Warning

This function has been DEPRECATED as of PHP 8.0.0. Relying on this function is highly discouraged.

Description

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.

Parameters

disable

Disable (true) or enable (false) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Return Values

Returns the previous value.

See Also

  • 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 Functions
  • Retrieve array of errors

libxml_get_errors

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

libxml_get_errors — Retrieve array of errors

Description

libxml_get_errors(): array

Retrieve array of errors.

Parameters

This function has no parameters.

Return Values

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Examples

Example #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";
}

?>

The above example will output:

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

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

See Also

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

libxml_get_external_entity_loader

(PHP 8 >= 8.2.0)

libxml_get_external_entity_loader — Get the current external entity loader

Description

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

Parameters

This function has no parameters.

Return Values

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.

See Also

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

Description

libxml_get_last_error(): LibXMLError|false

Retrieve last error from libxml.

Parameters

This function has no parameters.

Return Values

Returns a LibXMLError object if there is any error in the buffer, false otherwise.

See Also

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

Description

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

Parameters

resolver_function

A callable with the following signature:

resolver(?string $public_id, string $system_id, array $context): resource|string|null
public_id
The public ID.
system_id
The system ID.
context
An array with the four elements "directory", "intSubName", "extSubURI" and "extSubSystem".
This callable should return a resource, a string from which a resource can be opened. If null is returned, the entity reference resolution will fail.

Return Values

Returns true on success or false on failure.

Examples

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

The above example will output:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

See Also

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

Description

libxml_set_streams_context(resource $context): void

Sets the streams context for the next libxml document load or write.

Parameters

context

The stream context resource (created with stream_context_create())

Return Values

No value is returned.

Examples

Example #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');

?>

See Also

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

Description

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.

Parameters

use_errors

Enable (true) user error handling or disable (false) user error handling. Disabling will also clear any existing libxml errors.

Return Values

This function returns the previous value of use_errors.

Changelog

Version | Description
8.0.0 | use_errors is nullable now. Previously, its default was false.

Examples

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

?>

The above example will output:

bool(false)

See Also

  • 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

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild — Adds a child element to the XML node
    • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes — Identifies an element's attributes
    • SimpleXMLElement::children — Finds children of given node
    • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::current — Returns the current element
    • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
    • SimpleXMLElement::getName — Gets the name of the XML element
    • SimpleXMLElement::getNamespaces — Returns namespaces used in document
    • 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 — Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::rewind — Rewind to the first element
    • SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::valid — Check whether the current element is valid
    • SimpleXMLElement::xpath — Runs XPath query on XML data
  • SimpleXMLIterator — The SimpleXMLIterator class
  • SimpleXML Functions
    • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file — Interprets an XML file into an object
    • simplexml_load_string — Interprets a string of XML into an object

User Contributed Notes

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

function xmlObjToArr($obj) {

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

        }
        array_push($array,$row);
    }

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

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

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

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

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

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

<?php

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

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

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

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

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

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

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

2 line XML2Array:

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

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

<?php

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<?php

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

?>

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

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

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

or if it has childrens, that can be:

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

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

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

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

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

Use like this:

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

You can also pull multiple files in one array:

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

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

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

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

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

    $items = array();

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

    $child = (array)$obj;

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

    return $items;
}

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

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

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

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

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

    return "";
}

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

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

<?php

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

$xmlget = simplexml_load_string($xml)

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

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

exemple:

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

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

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

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

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

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

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

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

This will NOT work

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

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

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

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

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

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

For example, this does not work:

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

This will work:

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

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

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

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

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

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

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

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

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

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


Introduction

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --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


Examples

Table of Contents

  • Basic SimpleXML usage
  • Dealing with XML errors

User Contributed Notes

Juan Herrera 19-Dec-2009 12:49
When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;

$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500
info at accountr dot eu 05-May-2009 08:35
Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node = "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().
Kari P. 15-Aug-2008 02:17
To take care of proper error checking, one must use try-catch blocks:

<?php
try {
  $sxe = new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
  $sxe = @new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>
mike at mike-griffiths dot co dot uk 18-Apr-2008 09:11
It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Example #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#211;r</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

The above example will output:

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Example #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

The above example will output:

PHP solves all my web problems

Example #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Note:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Get attributes as element indices
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>

The above example will output:

7 thumbs up5 stars

Example #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

The above example will output:

My favorite movie.PHP: Behind the Parser

Example #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>

The above example will output:

bool(false)

Example #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Example #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

The above example will output:

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

Example #10 Adding elements and attributes

SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

The above example will output:

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

Example #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

The above example will output:

blah

User Contributed Notes

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

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

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

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

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

Instead you need to cast to string or int first:

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

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

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

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

So, I used this code,

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

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

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

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

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

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

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

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

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

SimpleXML objects follow four basic rules:

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

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

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

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

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

<?php

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

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

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

<?php

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

    $xmlDoc = new SimpleXMLElement($xml);

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

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

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

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

?>

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


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Example #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>

The above example will output:

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

See Also

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


The SimpleXMLElement class

(PHP 5, PHP 7, PHP 8)

Introduction

Represents an element in an XML document.

Class synopsis

class SimpleXMLElement implements Stringable, Countable, RecursiveIterator {
/* Methods */
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 | Description
8.0.0 | SimpleXMLElement implements Stringable, Countable, and RecursiveIterator now.

Table of Contents

  • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
  • SimpleXMLElement::addChild — Adds a child element to the XML node
  • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
  • SimpleXMLElement::attributes — Identifies an element's attributes
  • SimpleXMLElement::children — Finds children of given node
  • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::current — Returns the current element
  • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
  • SimpleXMLElement::getName — Gets the name of the XML element
  • SimpleXMLElement::getNamespaces — Returns namespaces used in document
  • 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 — Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::rewind — Rewind to the first element
  • SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::valid — Check whether the current element is valid
  • SimpleXMLElement::xpath — Runs XPath query on XML data

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.


Adds an attribute to the SimpleXML element

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Adds an attribute to the SimpleXML element

SimpleXMLElement::addAttribute

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

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

Description

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Adds an attribute to the SimpleXML element.

Parameters

qualifiedName

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

Return Values

No value is returned.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

The above example will output something similar to:

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

See Also

  • SimpleXMLElement::addChild() - Adds a child element to the XML node
  • Basic SimpleXML usage

User Contributed Notes

caffeinatedbits 09-Dec-2022 10:50
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo $animals->Dog->asXML();
// <Dog/>

?>
caffeinatedbits 09-Dec-2022 10:26
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
caffeinatedbits 09-Dec-2022 10:25
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
    foreach ($animals->Dog->attributes() as $attr => &$value) {
        if ("breed" === $attr) {
            $value = "poodle";
        }
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // An iterator cannot be used with foreach by reference
}

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
//     ["@attributes"]=>
//   array(1) {
//         ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


Adds a child element to the XML node

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Adds a child element to the XML node

SimpleXMLElement::addChild

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

SimpleXMLElement::addChild — Adds a child element to the XML node

Description

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Adds a child element to the node and returns a SimpleXMLElement of the child.

Parameters

qualifiedName

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

Return Values

The addChild method returns a SimpleXMLElement object representing the child added to the XML node on success; null on failure.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

The above example will output something similar to:

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

See Also

  • SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element
  • Basic SimpleXML usage

User Contributed Notes

fluxlicious at gmail dot com 23-Jan-2023 11:18
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
caffeinatedbits 09-Dec-2022 11:31
Just in case anyone else, like me, was trying to figure out a way to remove child elements...

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

unset($animals->Dog[2]);

echo $animals->asXML();

// <?xml version="1.0" encoding="utf-8"?>
// <Animals>
//         <Dog breed="chihuahua"/>
//         <Dog breed="poodle"/>
//
// </Animals>

?>

Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

$allowed_breeds = [
    'chihuahua',
    'poodle'
];

try {
    $index = 0;
    foreach ($animals->Dog as $dog) {
        if (!in_array($dog['breed'], $allowed_breeds)) {
            unset($animals->Dog[$index]);
        }
        $index++;
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // SimpleXMLElement is not properly initialized
}

?>
carlos dot eduardo dot debiasi at gmail dot com 22-Apr-2021 01:23
I create this function so you can through and array build the XML, this allows multiple keys with the same value.
The structure must follow

[
    'key' => 'nameOfTheKey',
    'attributes' => ['id' => '1'],
    'fields' => [
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '2'],
        ['key' => 'fieldWithChild', 'fields' => [
            ['key' => 'car', 'value' => '2'],
            ['key' => 'human', 'value' => '3'],
        ]],
    ]
];

Function:
 function toXml(\SimpleXMLElement $node, array $data)
    {
        foreach ($data as $key => $value) {
            $key = $value['key'];
            if (isset($value['value'])) {
                    $newNode = $node->addChild($key, $value['value']);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            } else {
                $newNode = $node->addChild($key);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            }
            if (isset($value['fields'])) {
                foreach ($value['fields'] as $keyField => $valueField) {
                    $this->toXml($newNode, [$keyField => $valueField]);
                }
            }
        }
    }
nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


Return a well-formed XML string based on SimpleXML element

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

Description

public SimpleXMLElement::asXML(?string $filename = null): string|bool

The asXML method formats the parent object's data in XML version 1.0.

Parameters

filename

If a string value is provided, the function writes the data to the file rather than returning it.

Return Values

If the filename isn't specified, this function returns a string on success and false on error. If the parameter is specified, it returns true if the file was written successfully and false otherwise.

Changelog

Version | Description
8.0.0 | filename is nullable now.

Examples

Example #1 Get XML

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

The above example will output:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo $node->asXML();
}
?>

The above example will output:

<c>text</c><c>stuff</c>

See Also

  • SimpleXMLElement::__toString() - Returns the string content
  • Basic SimpleXML usage

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr =
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>';

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ø, æ and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');


Identifies an element's attributes

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Identifies an element's attributes

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifies an element's attributes

Description

public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

namespaceOrPrefix

An optional namespace for the retrieved attributes

isPrefix

Default to false

Return Values

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns null if called on a SimpleXMLElement object that already represents an attribute and not a tag.

Examples

Example #1 Interpret an XML string

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

The above example will output:

name="one"
game="lonely"

See Also

  • Basic SimpleXML usage

User Contributed Notes

jurchiks101 at gmail dot com 23-May-2018 12:38
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes
(but not both) without type-casting is to use the function `current()`:

<?php
$xml = new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
    'bar' => [
        $xml->bar,
        current($xml->bar),
    ],
    'baz' => [
        $xml->baz->attributes(),
        current($xml->baz->attributes()),
    ],
    'qux' => [
        // won't work here correctly
        $xml->qux,
        current($xml->qux),
        $xml->qux->attributes(),
        current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
andy dot locologic+101 at gmail dot com 14-Aug-2015 10:00
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

<?php
      $x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
      $attributes = iterator_to_array($x->attributes());
?>
zevnikrok 18-Dec-2014 11:01
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
webfelipemaia at gmail dot com 07-Sep-2013 05:11
Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condição definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)

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

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/‎</link>
    </item>
</list>

Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.

<?php

$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {

        $role = $child->attributes();

        foreach($child as $key => $value) {

            if($role == "Language")
            echo("[".$key ."] ".$value . "<br />");

        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
adrian at foeder dot de 14-Jun-2013 10:15
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;
?>

This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.
totalwipeout at gmail dot com 08-Nov-2012 05:21
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $node is a SimpleXMLElement object

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after
$atts_array = $atts_array['@attributes'];

var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
                        //-             public '@attributes' => ...

var_dump($atts_array); //- outputs array (size=11) ...

?>
Hope this helps!
chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

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

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>


Finds children of given node

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Finds children of given node

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Finds children of given node

Description

public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

This method finds the children of an element. The result follows normal iteration rules.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

namespaceOrPrefix

An XML namespace.

isPrefix

If isPrefix is true, namespaceOrPrefix will be regarded as a prefix. If false, namespaceOrPrefix will be regarded as a namespace URL.

Return Values

Returns a SimpleXMLElement element, whether the node has children or not, unless the node represents an attribute, in which case null is returned.

Examples

Example #1 Traversing a children() pseudo-array

<?php
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');

foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];

foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';

foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
?>

The above example will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Example #2 Using namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
<foo:a>Apple</foo:a>
<foo:b>Banana</foo:b>
<c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

See Also

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - Counts all elements in an array or in a Countable object

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/>';
}
?>


Creates a new SimpleXMLElement object

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Creates a new SimpleXMLElement object

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

Description

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)

Creates a new SimpleXMLElement object.

Parameters

data

A well-formed XML string or the path or URL to an XML document if dataIsURL is true.

options

Optionally used to specify additional Libxml parameters, which affect reading of XML documents. Options which affect the output of XML documents (e.g. LIBXML_NOEMPTYTAG) are silently ignored.

Note:

It may be necessary to pass LIBXML_PARSEHUGE to be able to process deeply nested XML or very large text nodes.

dataIsURL

By default, dataIsURL is false. Use true to specify that data is a path or URL to an XML document instead of string data.

namespaceOrPrefix

Namespace prefix or URI.

isPrefix

true if namespaceOrPrefix is a prefix, false if it's a URI; defaults to false.

Errors/Exceptions

Produces an E_WARNING error message for each error found in the XML data and additionally throws an Exception if the XML data could not be parsed.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

The above example will output:

PHP: Behind the Parser

Example #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

See Also

  • Basic SimpleXML usage
  • simplexml_load_string() - Interprets a string of XML into an object
  • simplexml_load_file() - Interprets an XML file into an object
  • Dealing with XML errors
  • 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

Description

public SimpleXMLElement::count(): int

This method counts the number of children of an element.

Parameters

This function has no parameters.

Return Values

Returns the number of elements of an element.

Examples

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

The above example will output:

Person 1 has got 3 children.
Person 2 has got 5 children.

See Also

  • SimpleXMLElement::children() - Finds children of given node

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

Description

public SimpleXMLElement::current(): SimpleXMLElement
Warning

Prior to PHP 8.0, SimpleXMLElement::current() was only declared on the subclass SimpleXMLIterator.

This method returns the current element as a SimpleXMLElement object.

Parameters

This function has no parameters.

Return Values

Returns the current element as a SimpleXMLElement object.

Errors/Exceptions

Throws an Error on failure.

Changelog

Version | Description
8.1.0 | An Error is now thrown if SimpleXMLElement::current() is called on an invalid iterator. Previously, null was returned.

Examples

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

The above example will output:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

See Also

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


Returns namespaces declared in document

  • « SimpleXMLElement::current
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces declared in document

SimpleXMLElement::getDocNamespaces

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

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

Description

public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false

Returns namespaces declared in document

Parameters

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

fromRoot

Allows you to recursively check namespaces under a child node instead of from the root of the XML doc.

Return Values

The getDocNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example #1 Get document namespaces

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

?>

The above example will output:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Example #2 Working with multiple namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person t:id="1">John Doe</p:person>
<p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
Susie Q. Public
</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

The above example will output:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

See Also

  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the XML element

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Gets the name of the XML element

SimpleXMLElement::getName

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

SimpleXMLElement::getName — Gets the name of the XML element

Description

public SimpleXMLElement::getName(): string

Gets the name of the XML element.

Parameters

This function has no parameters.

Return Values

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Get XML element names

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}

?>

The above example will output:

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Returns namespaces used in document

  • « SimpleXMLElement::getName
  • SimpleXMLElement::getChildren »
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces used in document

SimpleXMLElement::getNamespaces

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

SimpleXMLElement::getNamespaces — Returns namespaces used in document

Description

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

Returns namespaces used in document

Parameters

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Return Values

The getNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

The above example will output:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

See Also

  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next 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

Description

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Warning

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.

Parameters

This function has no parameters.

Return Values

Returns a SimpleXMLElement object containing the sub-elements of the current element.

Examples

Example #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";
}
}
?>

The above example will output:

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

Description

public SimpleXMLElement::hasChildren(): bool
Warning

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.

Parameters

This function has no parameters.

Return Values

true if the current element has sub-elements, otherwise false

Examples

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

The above example will output:

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

Description

public SimpleXMLElement::key(): string
Warning

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.

Parameters

This function has no parameters.

Return Values

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

Errors/Exceptions

Throws an Error on failure.

Changelog

Version | Description
8.1.0 | An Error is now thrown if SimpleXMLElement::key() is called on an invalid iterator. Previously, false was returned.

Examples

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

?>

The above example will output:

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

Description

public SimpleXMLElement::next(): void
Warning

Prior to PHP 8.0, SimpleXMLElement::next() was only declared on the subclass SimpleXMLIterator.

This method moves the SimpleXMLElement to the next element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

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

The above example will output:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a prefix/ns context for the next XPath query

  • « SimpleXMLElement::next
  • SimpleXMLElement::rewind »
  • PHP Manual
  • SimpleXMLElement
  • Creates a prefix/ns context for the next XPath query

SimpleXMLElement::registerXPathNamespace

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

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

Description

public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

Parameters

prefix

The namespace prefix to use in the XPath query for the namespace given in namespace.

namespace

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Setting a namespace prefix to use in an XPath query

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

?>

The above example will output:

Chapter 1
Chapter 2

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

See Also

  • SimpleXMLElement::xpath() - Runs XPath query on XML data
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document

User Contributed Notes

Lea Hayes 12-Jan-2011 09:56
Looks like you have to use registerXPathNamespace for each node when using XPath:

<?php
$xml = simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// Breaks with out the following line:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>


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

Description

public SimpleXMLElement::rewind(): void
Warning

Prior to PHP 8.0, SimpleXMLElement::rewind() was only declared on the subclass SimpleXMLIterator.

This method rewinds the SimpleXMLElement to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

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

The above example will output:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Alias of SimpleXMLElement::asXML

  • « SimpleXMLElement::rewind
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Alias of SimpleXMLElement::asXML

SimpleXMLElement::saveXML

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

SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML()

Description

This method is an alias of: 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

Description

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.

Parameters

This function has no parameters.

Return Values

Returns the string content on success or an empty string on failure.

Examples

Example #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

The above example will output:

1 3

See Also

  • SimpleXMLElement::asXML() - Return a well-formed XML string based on SimpleXML element

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

Description

public SimpleXMLElement::valid(): bool
Warning

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

Parameters

This function has no parameters.

Return Values

Returns true if the current element is valid, otherwise false

Examples

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


Runs XPath query on XML data

  • « SimpleXMLElement::valid
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Runs XPath query on XML data

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Runs XPath query on XML data

Description

public SimpleXMLElement::xpath(string $expression): array|null|false

The xpath method searches the SimpleXML node for children matching the XPath expression.

Parameters

expression

An XPath path

Return Values

Returns an array of SimpleXMLElement objects on success; or null or false in case of an error.

Examples

Example #1 Xpath

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>

The above example will output:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

See Also

  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • Basic SimpleXML usage

User Contributed Notes

Filippo Vicari 28-Sep-2022 09:56
You can also search for siblings with a condition. For example immagine to need the title for a desidered language which with the two siblings tags in this XML file

<?xml version="1.0" encoding="UTF-8"?>
<IDOC BEGIN="1">
...
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>E</LANG>
    <TITLE>Name</TITLE>
    <LANG_ISO>EN</LANG_ISO>
</PRODUCT>
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>I</LANG>
    <TITLE>Name I</TITLE>
    <LANG_ISO>IT</LANG_ISO>
</PRODUCT>
...
</IDOC>

Let's break it down
<?php
"//PRODUCT" // find product tag
"//PRODUCT/LANG[.='E']" // whithin it find lang == "E"
"//PRODUCT/LANG[.='E']/../"  // go up one step
"//PRODUCT/LANG[.='E']/../TITLE" // get the title Tag content

// Combined search and find siblings ----------------------------
$xml = simplexml_load_file("fname.xml");

// Search for the TITLE field which sibling is == "E" ----------
$title_E_array = $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE"); // By default gives back an array of  SimpleXmlElement
$title = (string) $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE")[0]; // in this way saves only the value as a string
?>
awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


The SimpleXMLIterator class

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

Introduction

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

Class synopsis

class SimpleXMLIterator extends SimpleXMLElement {
/* Inherited methods */
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 | Description
8.0.0 | Iterator methods (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(),SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) were moved to SimpleXMLElement.
8.0.0 | SimpleXMLIterator implements Stringable now.

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 Functions

Table of Contents

  • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
  • simplexml_load_file — Interprets an XML file into an object
  • simplexml_load_string — Interprets a string of XML into an object

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.


Get a SimpleXMLElement object from a DOM node

  • « SimpleXML Functions
  • simplexml_load_file »
  • PHP Manual
  • SimpleXML Functions
  • Get a SimpleXMLElement object from a DOM node

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node

Description

simplexml_import_dom(SimpleXMLElement|DOMNode $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

Parameters

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Return Values

Returns a SimpleXMLElement or null on failure.

Examples

Example #1 Importing DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

The above example will output:

blah

See Also

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

User Contributed Notes

paul dot allsopp at digital-pig dot com 06-Jun-2023 12:07
Why not just:
simplexml_import_dom(dom_import_simplexml($SimpleXmlNode))
shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


Interprets an XML file into an object

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • SimpleXML Functions
  • Interprets an XML file into an object

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Interprets an XML file into an object

Description

simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Convert the well-formed XML document in the given file to an object.

Parameters

filename

Path to the XML file

class_name

You may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Bitwise OR of the libxml option constants.

namespace_or_prefix

Namespace prefix or URI.

is_prefix

true if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure.

Warning

This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Example #1 Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');

print_r($xml);
} else {
exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

See Also

  • simplexml_load_string() - Interprets a string of XML into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage
  • 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;
}
?>


Interprets a string of XML into an object

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • SimpleXML Functions
  • Interprets a string of XML into an object

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Interprets a string of XML into an object

Description

simplexml_load_string(
string $data,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Takes a well-formed XML string and returns it as an object.

Parameters

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Bitwise OR of the libxml option constants.

namespace_or_prefix

Namespace prefix or URI.

is_prefix

true if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or false on failure.

Warning

This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Example #1 Interpret an XML string

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

The above example will output:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

See Also

  • simplexml_load_file() - Interprets an XML file into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage

User Contributed Notes

erguven dot m at gmail dot com 11-May-2017 03:14
if you want to use a class which exists in a name space, use it full name. simple_load_string did not recognize short one.

class.new.php
<?php
namespace foo\bar;

class new extends SimpleXMLElement
{
    public function do()
    {
        echo "done";
    }
}
?>

false.php
<?php
use \foo\bar\new;

$result = simplexml_load_string($xml, 'new'); // it gives warning
$result->do(); // fatal error
?>

true.php
<?php
use \foo\bar\new;
$result = simplexml_load_string($xml, '\foo\bar\new');

$result->do(); // prints done
?>
artistan at gmail dot com 11-Jun-2015 12:32
Here is my update to Bob's simple SimpleXML wrapper function.
I noticed his version would turn an empty SimpleXMLElement into an empty array.

<?php
    /**
     * http://php.net/manual/en/function.simplexml-load-string.php#91564
     *
     * bool/array unserialize_xml ( string $input [ , callback $callback ] )
     * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
     * Returns false on all failure
     * Notes:
     * Root XML tags are stripped
     * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
     * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
     *
     * @param $input
     * @param null $callback
     * @param bool $recurse
     * @return array|mixed
     *
     */
    function unserialize_xml($input, $callback = null, $recurse = false)
    {
        // Get input, loading an xml string with simplexml if its the top level of recursion
        $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
        // Convert SimpleXMLElements to array
        if ($data instanceof SimpleXMLElement){
            if(!empty($data)){
                $data = (array) $data;
            } else {
                $data = '';
            }
        }
        // Recurse into arrays
        if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
        // Run callback and return
        return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
    }
?>
meustrus 07-May-2015 03:38
Be careful checking for parse errors. An empty SimpleXMLElement may resolve to FALSE, and if your XML contains no text or only contains namespaced elements your error check may be wrong. Always use `=== FALSE` when checking for parse errors.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Root xmlns:ns1="http://example.com/custom">
<ns1:Node>There's stuff here</ns1:Node>
</ns1:Root>
XML;

$simplexml = simplexml_load_string($xml);

// This prints "Parse Error".
echo ($simplexml ? 'Valid XML' : 'Parse Error'), PHP_EOL;

// But this prints "There's stuff here", proving that
// the SimpleXML object was created successfully.
echo $simplexml->children('http://example.com/custom')->Node, PHP_EOL;

// Use this instead:
echo ($simplexml !== FALSE ? 'Valid XML' : 'Parse Error'), PHP_EOL;

?>

See:

https://bugs.php.net/bug.php?id=31045
https://bugs.php.net/bug.php?id=30972
https://bugs.php.net/bug.php?id=69596
dkrnl at yandex dot ru 30-Sep-2013 02:58
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php
AllenJB 12-Oct-2012 08:09
<?php
$xml = json_decode(json_encode((array) simplexml_load_string($string)), 1);
?>

A reminder that json_encode attempts to convert data to UTF-8 without specific knowledge of the source encoding. This method can cause encoding issues if you're not working in UTF-8.
Anonymous 29-Feb-2012 08:54
Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/
Diego Araos, diego at klapmedia dot com 05-Feb-2011 12:57
A simpler way to transform the result into an array (requires json module).

<?php
function object2array($object) { return @json_decode(@json_encode($object),1); }
?>

Example:
<?php
$xml_object=simplexml_load_string('<SOME XML DATA');
$xml_array=object2array($xml_object);
?>
ascammon at hotmail dot com 28-Dec-2010 01:04
I had a hard time finding this documented, so posting it here in case it helps someone:

If you want to use multiple libxml options, separate them with a pipe, like so:

<?php
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
?>
jeff at creabilis dot com 17-Nov-2009 02:28
If you want to set the charset of the outputed xml, simply set the encoding attribute like this :

<?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?>

The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;.

Hope this help
Bob 17-Jun-2009 02:16
Here is my simple SimpleXML wrapper function.
As far as I can tell, it does the same as Julio Cesar Oliveira's (above).
It parses an XML string into a multi-dimensional associative array.
The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg).
<?php
function unserialize_xml($input, $callback = null, $recurse = false)
/* bool/array unserialize_xml ( string $input [ , callback $callback ] )
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
 * Returns false on all failure
 * Notes:
    * Root XML tags are stripped
    * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
    * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 */
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
    // Convert SimpleXMLElements to array
    if ($data instanceof SimpleXMLElement) $data = (array) $data;
    // Recurse into arrays
    if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
    // Run callback and return
    return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>
Julio Cesar Oliveira 30-Mar-2009 07:14
The XML2Array func now Recursive!

<?php
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }

    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}
?>
javalc6 at gmail dot com 18-Oct-2008 06:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.

Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.

<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>
rowan dot collins at gmail dot com 10-Jul-2008 07:07
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6

The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content.

<?php
$xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
    [0] => Text1 & XML entities
)
*/

$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?

// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
amir_abiri at ipcmedia dot com 08-Feb-2008 08:47
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} = $xml->number->{0} + 1;

echo $xml->asXml();
?>

echos:
<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>2</number></root>

However, this only works with a direct assignment, not with any of the other operators:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} += 1;
// Or:
$xml->number->{0}++;

echo $xml->asXml();
?>

Both of the above cases would result in:

<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>1<0/></number></root>
bojan 04-Feb-2008 04:38
As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect.
Consider the following:

<?php

// data in xml
$xml_txt = '
<root>
  <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>
  <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder>
</root>';

// load xml into SimpleXML object
$xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING

// see object structure
print_r($xml);

/* this prints
SimpleXMLElement Object
(
    [folder] => Array
        (
            [0] => aaaa
            [1] => bbbb
        )

)
*/

// but...
foreach ($xml->folder as $value){
    print_r($value);
}
/* prints complete structure of each folder element:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => aaaa
)

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => bbbb
)

*/
?>
hattori at hanso dot com 15-Oct-2007 03:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001

<?PHP
if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}
?>
nbijnens at servs dot eu 10-Sep-2007 05:17
Please note that not all LIBXML options are supported with the options argument.

For instance LIBXML_XINCLUDE does not work. But there is however a work around:

<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);

$xml->xinclude();
$xml = simplexml_import_dom($xml);

?>
Pedro 06-Jul-2007 01:28
Attention:

simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;).

Use numeric character references instead!
m dot ament at mailcity dot com 06-Mar-2007 06:51
Warning:

The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower 30-Jan-2007 03:03
A simple extension that adds a method for retrieving a specific attribute:

<?php
class simple_xml_extended extends SimpleXMLElement
{
    public    function    Attribute($name)
    {
        foreach($this->Attributes() as $key=>$val)
        {
            if($key == $name)
                return (string)$val;
        }
    }

}

$xml = simplexml_load_string('
<xml>
  <dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');

echo $xml->dog->Attribute('type');

?>

outputs 'poodle'

I prefer to use this technique rather than typecasting attributes.
Maciek Ruckgaber <maciekrb at gmai dot com> 07-Jun-2005 05:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P

when you have something like:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
?>

you will have the simpleXML object "transformed" to the text() content:

<?php
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328  (string)
?>
cellog at php dot net 31-Aug-2004 04:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx = simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
    if (is_string($val)) {
       // <one> will go here
    } elseif (is_array($val)) {
       // <multi> will go here because it happens multiple times
    } elseif (is_object($val)) {
      // <t> will go here because it contains tags
      // <two> will go here because it contains CDATA!
    }
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
    // this is not a tag that contains other tags
    $val = '' . $val;
    // now the CDATA is revealed magically.
}
?>


WDDX

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • wddx examples
  • WDDX Functions
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

There are no user contributed notes for this page.


Introduction

Warning

This extension is DEPRECATED and UNBUNDLED as of PHP 7.4.0.

These functions are intended for work with » WDDX.

Warning

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


Requirements

This extension requires the libxml PHP extension. This means passing the --with-libxml, or prior to PHP 7.4 the --enable-libxml, configuration flag, although this is implicitly accomplished because libxml is enabled by default.

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

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 7.4.0

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » 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.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

This extension defines a WDDX packet identifier returned by wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

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

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

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

Note:

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 Functions

Table of Contents

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header("Content-Type: text/xml;encoding=utf-8");
echo utf8_decode(wddx_serialize_value("안녕 하세요"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql = 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while($result = mysql_fetch_array($query)) {
    $id[] = $result[ 'id'];
    $name[] = $result['name'];
    $description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value = wddx_deserialize($packet);
print "pi is:<br>" . $value["pi"] . "<p>\n";
print "cities is:<br>\n";
while (list($key, $val) = each($value["cities"])) {
    print "$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>


Add variables to a WDDX packet with the specified ID

  • « WDDX Functions
  • wddx_deserialize »
  • PHP Manual
  • WDDX Functions
  • Add variables to a WDDX packet with the specified ID

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_add_vars(resource $packet_id, mixed $var_name, mixed ...$var_names): bool

Serializes the passed variables and add the result to the given packet.

Parameters

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

Return Values

Returns true on success or false on failure.

User Contributed Notes

maciek at webenlinea dot com 05-Sep-2004 11:20
Here is a simple way of serializing dynamic values from an array:

<?PHP
//a unix timestamp
$date    = "1094095513";

//some data to be included
$books   = array('programming'   => array('php','perl','java'),
                'markup'        => array('UML','XML','HTML')
                );

//stick data to an array to iterate over
$data_to_serialize = array($date,$books);

//create the packet
$packet = wddx_packet_start("SOME DATA ARRAY");

//loop through the data
foreach($data_to_serialize as $key => $data)
{
  //create a var whith the name of the content of $key
  $$key = $data;
  wddx_add_vars($packet,$key);
}

echo wddx_packet_end($packet);

?>

Have fun !


Unserializes a WDDX packet

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • WDDX Functions
  • Unserializes a WDDX packet

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Unserializes a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_deserialize(string $packet): mixed

Unserializes a WDDX packet.

Warning

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.

Parameters

packet

A WDDX packet, as a string or stream.

Return Values

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.

User Contributed Notes

valer underscore crisan at yahoo 01-Apr-2009 02:03
In PHP 5.2.9, we noticed that wddx serialize and deserialize seems to use UTF-8 encoding for XML input and the output data. There are some posts below that talk about fixing the input XML data so deserialize would work fine on special chars in ISO-8859-1 encoding, but none of the posts talks about the output encoding.

Consider this test:
$text = "Jür";
$packet = wddx_serialize_value($text);
$header = '<?xml version="1.0" encoding="iso-8859-1"?>';
$newText = wddx_deserialize($header . $packet);
echo "WDDX Packet: $packet\n";
echo "Deserialized Object: $newText\n";

The output is:

WDDX Packet: <wddxPacket version='1.0'><header/><data><string>Jür</string></data></wddxPacket>
Deserialized Object: JÃ¼r

The deserialized string is not in ISO-8859-1 encoding. It is in UTF-8 encoding. So we need to run utf8_decode() on the deserialized data to convert it back to ISO-8859-1 encoding which is what our application expects.

Hope this helps.
Magnus Deininger, dma05 at web dot de 12-Feb-2009 05:57
When writing your wddx file manually with an UTF-8 aware editor and saving it in utf-8, if your data gets its special characters mysteriously scrambled, try to add an xml header that marks the output as iso-8859-1, like this one:

<?xml version="1.1" encoding="iso-8859-1" ?>

This makes the wddx decode function treat the input as iso-8859-1, so it will not try to treat it as utf-8 and do an implicit decode to iso-8859-1. You will then have read all string data in the wddx packet in their original utf-8 encoding, so that 'echo' and other output functions will produce the intended result if you have set the output encoding to utf-8.

(Bugs reports on this behaviour seem to be treated as bogus, so it would seem in order to point out this incorrect and highly confusing side-effect.)
dormilich at netscape dot net 28-Nov-2008 05:13
When deserializing objects make sure you have the class definition loaded. wddx_deserialize() doesn't call the class itself, so you will receive a fatal error.
Nevertheless you can look for the class manually and delegate it to __autoload().

<?php
// $wddx_string needs to be valid XML to be loaded by SimpleXML.
// class_exists() will call the __autoload() function. if you don't
// want to use __autoloload(), use require_once()

function loadClassesFromWDDX($wddx_string)
{
    $xml = new SimpleXMLElement($wddx_string);

    foreach ($xml->xpath('//var') as $var)
    {
        if ($var['name'] == 'php_class_name')
        {
            if (!class_exists($var->string))
            {
                throw new Exception('Class '" . $var->string . "'not available.');
                // trigger_error('Class '" . $var->string . "'not available.', E_USER_ERROR);
            }
        }
    }
}
?>
dave at codexweb dot co dot za 21-Jan-2006 04:40
Here's a handy wddx_deserialize clone I wrote a while back. It uses PHP5 SimpleXML and recursion to do pretty much the same task as wddx_deserialize. Hope it comes in handy for someone.

<?php

if (!function_exists('wddx_deserialize'))
{
    /**
     * Clone implementation of wddx_deserialize
     */
    function wddx_deserialize($xmlpacket)
    {
        if ($xmlpacket instanceof SimpleXMLElement)
        {
            if (!empty($xmlpacket->struct))
            {
                $struct = array();
                foreach ($xmlpacket->xpath("struct/var") as $var)
                {
                    if (!empty($var["name"]))
                    {
                        $key = (string) $var["name"];
                        $struct[$key] = wddx_deserialize($var);
                    }
                }
                return $struct;
            }
            else if (!empty($xmlpacket->array))
            {
                $array = array();
                foreach ($xmlpacket->xpath("array/*") as $var)
                {
                    array_push($array, wddx_deserialize($var));
                }
                return $array;
            }
            else if (!empty($xmlpacket->string))
            {
                return (string) $xmlpacket->string;
            }
            else if (!empty($xmlpacket->number))
            {
                return (int) $xmlpacket->number;
            }
            else
            {
                if (is_numeric((string) $xmlpacket))
                {
                    return (int) $xmlpacket;
                }
                else
                {
                    return (string) $xmlpacket;
                }
            }
        }
        else
        {
            $sxe = simplexml_load_string($xmlpacket);
            $datanode = $sxe->xpath("/wddxPacket[@version='1.0']/data");
            return wddx_deserialize($datanode[0]);
        }
    }
}

?>
php dot net at werner-ott dot de 24-Nov-2005 12:20
On migrating wddx_deserialize() from PHP 4.x to PHP 5.1 (5.1.0RC6):

While

  $buffer = wddx_serialize_vars($some_array);
  $some_array = wddx_deserialize($buffer);

worked fine with PHP 4.x, the deserialization failed with PHP 5.1. In the above example $some_array will just be an empty string under 5.1

While wddx_serialize_vars() seems to behave identical in 4.x and 5.1, wddx_deserialize() does NOT.

Prepending XML encoding information to the buffer turned out to be at least a workaround. So, the following works with PHP 5.1:

  $buffer = wddx_serialize_vars($some_array);
  $buffer = '<?xml version="1.0"
          encoding="ISO-8859-1"?>'.
          $buffer;
  $some_array = wddx_deserialize($buffer);

NB: It may well be, that the behavioural difference between 4.x and 5.1 described above can only be observed if the array contains certain characters, i.e. german Umlaute (??????). So this workaround may not be necessary in each and every case.
mail_fidel at yahoo dot com 19-Nov-2004 12:11
To properly deserialize a wddx file it was to be utf8_encoded.

The following code will NOT work (PHP5.0.2 FreeBSD):

<?php
   $data = wddx_serialize_value(array("xyz???","abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>

Even thought the serialization is done right, the deserialization will not work unless you encode the text using utf8.

This code WILL work:

<?php
   $data = wddx_serialize_value(array(utf8_encode("xyz???"),"abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>
xavier at c-est-simple dot com 19-May-2004 04:09
JavaScript/PHP interroperability:

If you want to exchange wddx packets between a JavaScript application using the JS wddx library from openwddx (http://www.openwddx.org/downloads/), and a PHP script using wddx functions, be aware that the encoding of the classes of objects serialized in the wddx packet is not made the same way in both implementations.

The JS lib uses a 'type' attribute in the 'struct' tab and gives it the name of the class of the object serialized in the 'struct' element, while PHP uses a 'php_class_name' tag within the 'struct'.
NB : to get the type attribute with JS serialisation, you need to set the 'wddxSerializationType' member in your classes

Example with an object of class 'exemple' containing 2 members _attr1 and _attr2.
(NB : in french, 'example' is spelled 'exemple', okay ? :-)

JS serialization :
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct type="exemple">
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

php serialization:
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct>
   <var name='php_class_name'>
    <string>exemple</string>
   </var>
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

I like the JS approach better.
So if you need the compatibility, the workaround is quite simple:
- add a 'php_class_name' member in your JS objects, giving it the name of the class for value, and the JS generated packet will be correctly deserialized with PHP in classed objects.

- use a regexp on a PHP generated packet to add the 'type' attribute so that the JS deserialization instanciates objects of the right class:
      $pat = "/<struct><var name='php_class_name'><string>(\w+)<\/string>/" ;
      $rep = "<struct type='\$1'><var name='php_class_name'><string>\$1</string>" ;
      $serialised = preg_replace($pat, $rep, $serialised );
NB : this only works because the 'php_class_name' tag is just next to the 'struct' tag.
Who knows if this is going to be true in future releases... ?

This way, you can exchange JS and PHP objects (provided you define your JS and PHP classes the same way) smoothly...

It's worth saying that both implementations, as well as my interroperability workaround, handle correctly objects with members that are also objects.

NB : NB means Nota Bene.
xavier at c-est-simple.com 18-May-2004 10:19
Beware, although the deserialized objects are instanciated class objects (if the php_class_name tag is amongst the children of the struct tag and its text content is the name of a loaded class), the constructor of the class has not been called at all.
You can use the members and call the methods of the object all right, but any initialisation action that the constructor might be in charge of is missing.
php at mike2k dot com 10-Sep-2001 06:06
if you have WDDX data coming from a third party source and it isnt being parsed correctly in your php, try translating their WDDX. we have a third party sending us WDDX from cold fusion, and it uses a <recordset> element, which PHP seems to ignore (looking around the web we found some other people having trouble) so the (hopefully temporary) solution we found was to translate the WDDX midstream and then we were able to parse it:

$url = "http://somedomain.com/blah.wddx";
$fp = fopen($url,"r");
$page = fread($fp,10000);
fclose($fp);
$page = str_replace("<recordset","<struct",$page);
$page = str_replace("</recordset","</struct",$page);
$page = str_replace("<field","<var",$page);
$page = str_replace("</field","</var",$page);
$values = wddx_deserialize($page);
while(list($key,$val) = each($values)) {
        print "$key => $val<BR>";
}

this works for us. it's a hack, and hopefully php will support this in the future or something.
medvitz at medvitz dot net 14-Oct-2000 05:29
You can also serialize instantiated class objects with the wddx functions.
ie.

<?php
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "objvar");
$packet = wddx_packet_end($packet_id);

$a =  wddx_deserialize($packet);
$obj = $a[objvar];
?>

now $obj is a useable object, that looks like the original.

Note that with this method, you need to know what the variable name of the original object was.  You can use one of the array functions to get the object in the event that the original object's variable name was unknown.

*** only verified on linux with 4.0.2
djm at web dot us dot uu dot net 18-Oct-1999 09:58
The packet string you pass to this function doesn't have to be sanitized first; it searches for a WDDX packet within the string.  So the string can contain HTML markup and random text outside of the packet, and that is all ignored.
This means you can get a packet from another web page like this:
<?php
$fhandle = fopen("http://myserver.com/packet.php", "r");
if ($fhandle) {
        $page = fread($fhandle,10000);
        fclose($fhandle);
        $value = wddx_deserialize($page);
        print "pi is:<br>" . $value["pi"] . "<p>\n";
} else {
        print "could not get packet.php<p>";
}
?>


Ends a WDDX packet with the specified ID

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • WDDX Functions
  • Ends a WDDX packet with the specified ID

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Ends a WDDX packet with the specified ID

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_packet_end(resource $packet_id): string

Ends and returns the given WDDX packet.

Parameters

packet_id

A WDDX packet, returned by wddx_packet_start().

Return Values

Returns the string containing the WDDX packet.

User Contributed Notes

There are no user contributed notes for this page.


Starts a new WDDX packet with structure inside it

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • WDDX Functions
  • Starts a new WDDX packet with structure inside it

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_packet_start(string $comment = ?): resource

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Parameters

comment

An optional comment string.

Return Values

Returns a packet ID for use in later functions, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Serialize a single value into a WDDX packet

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • WDDX Functions
  • Serialize a single value into a WDDX packet

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serialize a single value into a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_serialize_value(mixed $var, string $comment = ?): string

Creates a WDDX packet from a single given value.

Parameters

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Return Values

Returns the WDDX packet, or false on error.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen


Serialize variables into a WDDX packet

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • WDDX Functions
  • Serialize variables into a WDDX packet

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serialize variables into a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Parameters

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

Return Values

Returns the WDDX packet, or false on error.

Examples

Example #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

The above example will output:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

User Contributed Notes

kangus at jaga dot us 13-Oct-2003 03:57
A function to use for dates with PHP & WDDX
getdate()

$ta="<FORM><TEXTAREA rows=15 cols=80>" ;
$te="</TEXTAREA></FORM>";
$packet_id=wddx_packet_start("Date Example--");
$myDate=getdate();
wddx_add_vars($packet_id,'myDate');
$package=wddx_packet_end($packet_id);
print($ta.$package.$te);

Produces:

<wddxPacket version='1.0'><header><comment>Date Example--</comment></header>
<data><struct><var name='myDate'>
<struct><var name='seconds'><number>12</number></var>
<var name='minutes'><number>55</number></var>
<var name='hours'><number>1</number></var>
<var name='mday'><number>13</number></var>
<var name='wday'><number>1</number></var>
<var name='mon'><number>10</number></var>
<var name='year'><number>2003</number></var>
<var name='yday'><number>285</number></var>
<var name='weekday'><string>Monday</string></var>
<var name='month'><string>October</string></var>
<var name='0'><number>1066031712</number>
</var></struct></var></struct></data></wddxPacket>
tychay at alumni dot caltech dot edu 31-Mar-2002 12:15
The above feature will cause a slight trouble since the name of the variable will always be "wddxtemp" but you can use preg_replace to fix that.

Also, a better approach is to serialize the entire class. WDDX will that write a reserved "php_class_name" variable which can be used to reconstruct the class during a deserialize.
tychay at alumni dot caltech dot edu 30-Mar-2002 10:49
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
tychay at alumni dot caltech dot edu 30-Mar-2002 10:45
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
christian dot knoflach at gmx dot at 21-May-2001 03:56
Be careful using WDDX - functions on object variables. As I just had to find out the following won't work:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx = wddx_serialize_vars("this->str");
    print(htmlentities($this->wddx));
  }
}

new Test();
?>

That's what you'll get:
<wddxPacket version='1.0'><header/><data><struct></struct></data></wddxPacket>


XML diff and merge

  • Introduction
  • Installing/Configuring
    • Requirements
    • 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.


Introduction

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.


Requirements

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

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » 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)

Introduction

Base abstract class for all the comparsion classes in the extension.

Class synopsis

class XMLDiff\Base {
/* Methods */
public __construct(string $nsname)
abstract public diff(mixed $from, mixed $to): mixed
abstract public merge(mixed $src, mixed $diff): mixed
}

Table of Contents

  • 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

Description

public XMLDiff\Base::__construct(string $nsname)

Base constructor for all the worker classes in the xmldiff extension.

Parameters

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

Description

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.

Parameters

from

Source XML document.

to

Target XML document.

Return Values

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

Description

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.

Parameters

src

Source XML document.

diff

Document produced by the diff method.

Return Values

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

Introduction

Class synopsis

class XMLDiff\DOM extends XMLDiff\Base {
/* Methods */
public diff(DOMDocument $from, DOMDocument $to): DOMDocument
public merge(DOMDocument $src, DOMDocument $diff): DOMDocument
/* Inherited methods */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Table of Contents

  • 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

Description

public XMLDiff\DOM::diff(DOMDocument $from, DOMDocument $to): DOMDocument

Diff two DOMDocument instances and produce the new one containing the diff information.

Parameters

from

Source DOMDocument object.

to

Target DOMDocument object.

Return Values

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

Description

public XMLDiff\DOM::merge(DOMDocument $src, DOMDocument $diff): DOMDocument

Create new DOMDocument based on the diff.

Parameters

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

Return Values

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)

Introduction

Class synopsis

class XMLDiff\Memory extends XMLDiff\Base {
/* Methods */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Inherited methods */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Table of Contents

  • 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

Description

public XMLDiff\Memory::diff(string $from, string $to): string

Diff two strings containing XML documents and produce the diff information.

Parameters

from

Source XML document.

to

Target XML document.

Return Values

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

Description

public XMLDiff\Memory::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parameters

src

Source XML document.

diff

XML document containing diff information.

Return Values

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)

Introduction

Class synopsis

class XMLDiff\File extends XMLDiff\Base {
/* Methods */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Inherited methods */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Table of Contents

  • 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

Description

public XMLDiff\File::diff(string $from, string $to): string

Diff two local XML files and produce string with the diff information.

Parameters

from

Path to the source document.

to

Path to the target document.

Return Values

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

Description

public XMLDiff\File::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parameters

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

Return Values

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


XML Parser

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Event Handlers
  • Case Folding
  • Error Codes
  • Character Encoding
  • Examples
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • XML Parser Functions
    • 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.


Introduction

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.


Requirements

This extension requires the libxml PHP extension. This means passing the --with-libxml, or prior to PHP 7.4 the --enable-libxml, configuration flag, although this is implicitly accomplished because libxml is enabled by default.

This extension uses an expat compat layer by default. It can use also expat, which can be found at » http://www.jclark.com/xml/expat.html. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
A source RPM package of expat can be found at » http://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.


Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --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.

The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

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.


Resource Types

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.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XML_ERROR_NONE (int)
XML_ERROR_NO_MEMORY (int)
XML_ERROR_SYNTAX (int)
XML_ERROR_NO_ELEMENTS (int)
XML_ERROR_INVALID_TOKEN (int)
XML_ERROR_UNCLOSED_TOKEN (int)
XML_ERROR_PARTIAL_CHAR (int)
XML_ERROR_TAG_MISMATCH (int)
XML_ERROR_DUPLICATE_ATTRIBUTE (int)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (int)
XML_ERROR_PARAM_ENTITY_REF (int)
XML_ERROR_UNDEFINED_ENTITY (int)
XML_ERROR_RECURSIVE_ENTITY_REF (int)
XML_ERROR_ASYNC_ENTITY (int)
XML_ERROR_BAD_CHAR_REF (int)
XML_ERROR_BINARY_ENTITY_REF (int)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (int)
XML_ERROR_MISPLACED_XML_PI (int)
XML_ERROR_UNKNOWN_ENCODING (int)
XML_ERROR_INCORRECT_ENCODING (int)
XML_ERROR_UNCLOSED_CDATA_SECTION (int)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (int)
XML_OPTION_CASE_FOLDING (int)
XML_OPTION_TARGET_ENCODING (int)
XML_OPTION_SKIP_TAGSTART (int)
XML_OPTION_SKIP_WHITE (int)
XML_SAX_IMPL (string)
Holds the SAX implementation method. Can be libxml or expat.

User Contributed Notes

There are no user contributed notes for this page.


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

The following constants are defined for XML error codes (as returned by xml_parse()):

  • XML_ERROR_NONE
  • XML_ERROR_NO_MEMORY
  • XML_ERROR_SYNTAX
  • XML_ERROR_NO_ELEMENTS
  • XML_ERROR_INVALID_TOKEN
  • XML_ERROR_UNCLOSED_TOKEN
  • XML_ERROR_PARTIAL_CHAR
  • XML_ERROR_TAG_MISMATCH
  • XML_ERROR_DUPLICATE_ATTRIBUTE
  • XML_ERROR_JUNK_AFTER_DOC_ELEMENT
  • XML_ERROR_PARAM_ENTITY_REF
  • XML_ERROR_UNDEFINED_ENTITY
  • XML_ERROR_RECURSIVE_ENTITY_REF
  • XML_ERROR_ASYNC_ENTITY
  • XML_ERROR_BAD_CHAR_REF
  • XML_ERROR_BINARY_ENTITY_REF
  • XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
  • XML_ERROR_MISPLACED_XML_PI
  • XML_ERROR_UNKNOWN_ENCODING
  • XML_ERROR_INCORRECT_ENCODING
  • XML_ERROR_UNCLOSED_CDATA_SECTION
  • XML_ERROR_EXTERNAL_ENTITY_HANDLING

User Contributed Notes

Teet 24-May-2019 02:04
If you wonder, what values those constant have, here you go:

<?php
XML_ERROR_NONE = 0
XML_ERROR_NO_MEMORY = 1
XML_ERROR_SYNTAX = 2
XML_ERROR_NO_ELEMENTS = 3
XML_ERROR_INVALID_TOKEN = 4
XML_ERROR_UNCLOSED_TOKEN = 5
XML_ERROR_PARTIAL_CHAR = 6
XML_ERROR_TAG_MISMATCH = 7
XML_ERROR_DUPLICATE_ATTRIBUTE = 8
XML_ERROR_JUNK_AFTER_DOC_ELEMENT = 9
XML_ERROR_PARAM_ENTITY_REF = 10
XML_ERROR_UNDEFINED_ENTITY = 11
XML_ERROR_RECURSIVE_ENTITY_REF = 12
XML_ERROR_ASYNC_ENTITY = 13
XML_ERROR_BAD_CHAR_REF = 14
XML_ERROR_BINARY_ENTITY_REF = 15
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF = 16
XML_ERROR_MISPLACED_XML_PI = 17
XML_ERROR_UNKNOWN_ENCODING = 18
XML_ERROR_INCORRECT_ENCODING = 19
XML_ERROR_UNCLOSED_CDATA_SECTION = 20
XML_ERROR_EXTERNAL_ENTITY_HANDLING = 21
?>


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.


Examples

Table of Contents

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

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

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

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

?>

Example #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:

Example #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 Functions

Table of Contents

  • 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 Functions
  • xml_get_current_byte_index »
  • PHP Manual
  • XML Parser Functions
  • Get XML parser error string

xml_error_string

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

xml_error_string — Get XML parser error string

Description

xml_error_string(int $error_code): ?string

Gets the XML parser error string associated with the given error_code.

Parameters

error_code

An error code from xml_get_error_code().

Return Values

Returns a string with a textual description of the error error_code, or null if no description was found.

See Also

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

Description

xml_get_current_byte_index(XMLParser $parser): int

Gets the current byte index of the given XML parser.

Parameters

parser

A reference to the XML parser to get byte index from.

Return Values

Returns which byte index the parser is currently at in its data buffer (starting at 0).

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

Notes

Warning

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

See Also

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

Description

xml_get_current_column_number(XMLParser $parser): int

Gets the current column number of the given XML parser.

Parameters

parser

A reference to the XML parser to get column number from.

Return Values

Returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

See Also

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

Description

xml_get_current_line_number(XMLParser $parser): int

Gets the current line number for the given XML parser.

Parameters

parser

A reference to the XML parser to get line number from.

Return Values

Returns which line the parser is currently at in its data buffer.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

See Also

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

Description

xml_get_error_code(XMLParser $parser): int

Gets the XML parser error code.

Parameters

parser

A reference to the XML parser to get error code from.

Return Values

Returns one of the error codes listed in the error codes section.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

See Also

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

Description

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.

Parameters

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.

Return Values

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 | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

Examples

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:

Example #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:

Example #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:

Example #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 Functions
  • Start parsing an XML document

xml_parse

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

xml_parse — Start parsing an XML document

Description

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.

Parameters

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.

Return Values

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

Note:

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 | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

Examples

Example #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 Functions
  • 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

Description

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.

Parameters

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.

Return Values

Returns a new XMLParser instance.

Changelog

Version | Description
8.0.0 | This function returns an XMLParser instance now; previously, a resource was returned, or false on failure.
8.0.0 | encoding is nullable now.

See Also

  • 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 Functions
  • Create an XML parser

xml_parser_create

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

xml_parser_create — Create an XML parser

Description

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.

Parameters

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.

Return Values

Returns a new XMLParser instance.

Changelog

Version | Description
8.0.0 | This function returns an XMLParser instance now; previously, a resource was returned, or false on failure.
8.0.0 | encoding is nullable now.

See Also

  • 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 Functions
  • Free an XML parser

xml_parser_free

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

xml_parser_free — Free an XML parser

Description

xml_parser_free(XMLParser $parser): bool

Note:

This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.

Frees the given XML parser.

Caution

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.

Parameters

parser
A reference to the XML parser to free.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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

Description

xml_parser_get_option(XMLParser $parser, int $option): string|int|bool

Gets an option value from an XML parser.

Parameters

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.

Return Values

Returns the option's value.

Errors/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 | Description
8.3.0 | The function now returns a boolean for boolean options.
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.
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 Functions
  • 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

Description

xml_parser_set_option(XMLParser $parser, int $option, string|int|bool $value): bool

Sets an option in an XML parser.

Parameters

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.

Return Values

Returns true on success or false on failure.

Errors/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 | Description
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 expects an XMLParser instance now; previously, a valid xml resource was expected.
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 Functions
  • 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

Description

xml_set_character_data_handler(XMLParser $parser, callable $handler): true

Sets the character data handler function for the XML parser parser.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
The XML parser calling the handler.
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).

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

User Contributed Notes

svanegmond at tinyplanet dot ca 08-Oct-2010 12:06
For those who are having their character entities eaten by this function (e.g. &amp; &lt; and so forth):

You will notice that your callback gets called several times.

input: Give me some beans &amp; rice. &#032;

call 1: Give me some beans
call 2: amp; and rice
call 3: #032;

There is an obvious workaround. This is not perfect:

<?php
        $text = preg_replace('/^([a-z]+;)/','&\1', $text);
        $text = preg_replace('/^(#[0-9]+;)/', '&\1', $text);
?>
jhill at live dot com 28-Aug-2008 07:11
To detect that concatenation of data is taking place, you can keep track of whether the last function call was to the data processing function.
e.g. using $this->inside_data variable below:

<?php
xml_set_element_handler($this->parser, "start_tag", "end_tag");
xml_set_character_data_handler($this->parser, "contents");

protected function contents($parser, $data)
{
    switch ($this->current_tag) {
            case "name":
                if ($this->inside_data)
                    $this->name .= $data; // need to concatenate data
                else
                    $this->name = $data;
                break;
         ...
    }
    $this->inside_data = true;
}

protected function start_tag($parser, $name)
{
    $this->current_tag = $name;
    $this->inside_data = false;
}

protected function end_tag() {
    $this->current_tag = '';
    $this->inside_data = false;
}
?>
unspammable-iain at iaindooley dot com 03-Jan-2006 01:41
re: jason at omegavortex dot com below, another way to deal with whitespace issues is:

        function charData($parser,$data)
        {
            $char_data = trim($data);

            if($char_data)
                $char_data = preg_replace('/  */',' ',$data);

            $this->cdata .= $char_data;
        }

This means that:

    <p>here is my text <a href="something">my text</a>
    and here is some more after some spaces at the
    beginning of the line</p>

comes out properly. You could do further replacements if you want to deal with tabs in your files. i only ever use spaces. if you only use trim() then you would lose the space before the <a> tag above, but trim() is a good way to check for completely empty char data, then just replace more than one space with a single space. this will preserve a single space at the beginning and end of the cdata.
jason at omegavortex dot com 06-Dec-2005 11:00
I don't believe the problem has been addressed, but if you're parsing an XML file and run into the line break (or tab) problem I believe this function may help:

if (!preg_match("/((\r|)\n)/i", $data) || preg_match("/\\t+/i", $data)) {
(Code Here)
}
wako057 at gmx dot fr 22-Aug-2005 09:39
That give an example about the note.
When you are creating a class and you need to use a method of your class to the function xml_set_character_data_handler that is the way to point give the method:

class example
{
   function example()
   {
   }

  function data($parseur, $texte)
  {
      switch ($this->derniereBaliseRencontree)
      {
         case "TITLE":
                     -----
          break;
         case "LINK"
                    -----
         break;
        case "DESCRIPTION":
                    -----
        break;
     }
  }

  function fetchOpen($parseur, $nomBalise, $tableauAttributs)
  {
     ----------------
  }

  function fetchClose($parseur, $nomBalise)
  {
     ----------------
  }

  function ZZZ()
  {
      $parseurXML = xml_parser_create();
       xml_set_element_handler($parseurXML, Array(&$this, 'fetchOpen'),   Array(&$this, 'fetchClose'));
         ---------------- <IMPORTANT> --------------------------
       xml_set_character_data_handler($parseurXML, Array(&$this, 'data'));
        ---------------- </IMPORTANT> --------------------------
}
ben at removethis emediastudios dotcom 05-Aug-2005 03:53
I too love the undocumented "splitting" functionality :-p.

Rather than concatinating the data based on whether or not the current tag name has changed from the previous tag name I suggest always concatinating like the following with the $catData variable being unset in the endElement function:

<?php

function endElement ($parser, $data) {
  global $catData;

  // Because we are at an element end we know any splitting is finished
  unset($GLOBALS['catData']);
}

function characterData ($parser, $data) {
  global $catData;

  // Concatinate data in case splitting is taking place
  $catData.=$data;

}

?>

This got me around a problem with data like the following where, because characterData is not called for empty tags, the previous and current tag names were the same even though splitting was not taking place.

<companydept>
<companydeptID></companydeptID>
<companyID>1</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>2</companyID>
<companydeptName></companydeptName>
</companydept>
<companydept>
<companydeptID></companydeptID>
<companyID>3</companyID>
<companydeptName></companydeptName>
</companydept>
yaroukh at email dot cz 25-Apr-2005 08:51
It would be nice if someone could complete documentation of this function. I think that the "splitting" behaviour should (at least) be mentioned within the documentation, if not explained (please!). I'm not quite sure whether the cut comes after each 1024bytes/chars of data.

My experience looks as follows:
[xmlFile]
...
    <label>slo|?ka</label>
    <comment>koment|?&#345; slo?ky</comment>
...
[/xmlFile]
(Places where the character-data got splitted are marked with pipes. Plus there was latin small letter 'r' with caron instead of &#345;.)

Since the splitting is not mentioned in documentation one could assume that it is a bug; especially when you work with UTF-8 and the cuts come right before some special characters.
(Should the concatenating of $cData be considered to be the proper & 'final' way of processing character-data?)

Also I'd suggest to add another line in "Description" when fc has an alternate usage (instead of hiding it within the "Note" :o); in this particular case I'd prefer this:

Description:
bool xml_set_character_data_handler ( resource parser, callback handler )
bool xml_set_character_data_handler ( resource parser, object reference, method name )

... there are dozens of functions ofcourse where documentation works this way (I mean not mentioning the alternate usage in the "Description" part).

Have a nice day
  Yaroukh
flobee 12-Feb-2005 09:53
re. to Philippe Marc , and  karuna_gadde examples

i found out that the xml_set_character_data_handler call back  function can be called more often for the same element in particular the content is just a few chars long (happen on windows)

so a check up can give you the answer an may be for long strings too.
eg:
<?php
xml_set_character_data_handler($this->parser, "cdata");
//...
function cdata($parser, $cdata) {
// ...
if(isset($this->data[$this->currentItem][$this->currentField])) {
    $this->data[$this->currentItem][$this->currentField] .= $cdata;
} else {
    $this->data[$this->currentItem][$this->currentField] = $cdata;
}
?>
Philippe Marc 28-Oct-2004 07:21
How to overide the 1024 characters limitation of xml_set_character_data_handler.
Took me some time to find out how to deal with that!

When calling a basic XML parser:
$parseurXML = xml_parser_create();
xml_set_element_handler($parseurXML, "opentagfunction", "closetagfunction");
xml_set_character_data_handler($parseurXML, "textfunction");

The textfunction only receive 1024 characters at once, even if the text is 4000 characters long. In facts, the parser seems to split the data in pieces of 1024 characters. The way to handle that is to concatenate them.

example:
If you have an XML tag called UNIPROT_ABSTRACT containing a 4000 characters protein description:
function textfunction($parser, $text)
    {
     if ($last_tag_read=='UNIPROT_ABSTRACT') $uniprot.=$text;
    }
The function is called 4 times and receives 1024+1024+1024+928 characters that will be concatenated in the $uniprot variable using the ".=" concatenation fonction.

Easy to do, but not documented!
Brad dot Harrison at griffith dot edu dot au 11-Jul-2004 10:23
If you need to trim the white space for HTML code and don't rely on spaces for formatting text (if you are then it is time to use Style Sheets) then this code will come in very useful.

 $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
 $data=eregi_replace(">"."[[:space:]]+",">",$data);
 $data=eregi_replace("[[:space:]]+"."<","<",$data);
karuna_gadde at yahoo dot com 27-May-2004 07:01
<?
class Parser {

var $att;
var $id;
var $title;
var $content;
var $index=-1;
var $xml_parser;
var $tagname;

function parser()
{
$file = "data.xml";
$this->xml_parser = xml_parser_create();
xml_set_object($this->xml_parser,$this);
xml_set_element_handler($this->xml_parser, "startElement", "endElement");
xml_set_character_data_handler($this->xml_parser, 'elementContent');
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
if (!xml_parse($this->xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->xml_parser)),
xml_get_current_line_number($this->xml_parser)));
}
}
xml_parser_free($this->xml_parser);
}

function startElement($parser, $name, $attrs) {
if (($name=="TREE") or ($name=="NODE") or ($name=="LEAFNODE"))
    {
         $this->index++;
         $this->att[$this->index]=$name;
    }
    $this->tagname=$name;
}

function elementContent($parser, $data) {
switch ($this->tagname)
{
     case 'ID':
                 $this->id[$this->index]=trim($data);
                 break;
     case 'TITLE' :
                 $this->title[$this->index]=trim($data);
                 //echo $data;
                 break;
     case 'CONTENT'    :
                 $this->content[$this->index]=trim($data);
                 break;

}
}
function endElement($parser, $name){
$this->tagname=="";
}
}
?>

I thought this class is more help full to know about xml_parser with no white spaces
michael dot stilson at wmich dot edu 04-Mar-2004 12:31
Hello,

This is an addition to the note posted by:
wiart at yahoo dot com
22-Aug-2003 05:31
Which is located below.

I had similar problems manually creating XML docs and adding new-lines within my node data, e.g.

<root>
    ...
    <node attribute="something">
        Here is some data. There is a lot of data, and I want to
        be able to read the data from a terminal window, so I add
        newlines to fit everything within 80 columns.
    </node>
    ...
</root>

So, given the above example, my data handler gets called 3 times and the result left in my variable is:

"newlines to fit everything within 80 columns."

Instead of all of the data within "node", which I was expecting.

By using the concatenation operator; however, as suggested by the mentioned note, I was able to get what I needed. Which is of course:

"Here is some data. There is a lot of data, and I want to be able to read the data from a terminal window, so I add newlines to fit everything within 80 columns."
dan30odd08 at hotmail dot com 01-Dec-2003 04:38
I just want to mention that i ran into a problem when parsing an xml file using the character data handler. If you happen to have a string which is also an internal php function stored in your xml data file and you want to output it as a string the parser dosent seem to recognize it.
   I found a way around this problem. In my case i was storing a string with the value read. This would not allow me to output the data so to work around this problem i added a backslash for every character in the data element.

   e.g.      <xml>
    from    <element>read</element>
    to       <element>////read</element>

i dont know if anyone has ran into this problem or not but i thought i would just put it here just so in case someone is getting stuck with this.
wiart at yahoo dot com 22-Aug-2003 05:31
WARNING !!!
Always use concatenation for getting the content of a XML tag when you write the function that will deal with the Character Data handling

Example:

$mycontent = '';
$xml_parser = xml_parser_create ();
xml_set_character_data_handler($xml_parser, "_characterdata");

function _characterdata($parser, $data){
  global $mycontent;
  //HERE: use .= and not =
  $mycontent .= $data;
}

...

while ($data = fread($fp, 4096)) {
    xml_parse($xml_parser, $data, feof($fp));
}

I had the following problem with the use of '=$data' :

In one of my XML documents, the parsing stopped in the middle of a character data :

In original document:
<prop name="nbres">100</prop>

What happened:
<prop name="nbres">10[parsing stopped here in chunck of 4096bytes]0</prop>

As I did not use the concatenation, when I displayed the value of the 'nbres' property, the value was 0 instead of 100 because the first time the function characterdata was called :
$mycontent = 10;

and the second time:
$mycontent = 0;      //!!!!!!!!!!!!! HO HO !! some problem occured ...

Instead of $mycontent = 100;

CONCLUSION:
IN YOUR CHARACTER DATA HANDLER FUNCTIONS, NEVER FORGET THE . (concatenation operator) !!!!! IF YOU DON'T WANT TO HAVE WEIRD BUGS SOME TIMES
morris_hirsch at hotmail dot com 18-Aug-2003 09:15
Thanks to Christian Stocker for clearing up my entity issues,  where some entities are parsed correctly and others not.

The problem is the ''wide'' entities that have a large numeric code simply can not fit in a single byte, which is the default encoding for both source input to the parser and data output from the parser.  So the parser puts out a ''?'' to say it could not store the code value. One could argue that if the input has a &1234; the output should simply copy it as &1234; instead of the ''?'' but that would still mean the  parser behaves two different ways according to the code values, and anyway they don't do it.

So, we need utf8 encoding for the output, and the slightly not obvious way to say so is

  $xml_parser = xml_parser_create ("UTF-8");

which means BOTH source input and data output are utf8.
Remember that utf8 is a superset of basic ASCII but not of extended ASCII, so your input can contain e.g. &eacute;
spelled out, but a native eacute character is wrong here.
Just utf8_encode your input to be sure.

That should do it, and thanks again for the help.
morris_hirsch at hotmail dot com 06-Aug-2003 12:23
Here are two ways to deal with named entities in the XML.

1. Put a list of named entities at the front so the parser knows what they all mean

  $decl = '<!DOCTYPE rootname [

<!ENTITY frac12  "&#x00BD;" >
<!ENTITY frac14  "&#x00BC;" >
<!ENTITY frac34  "&#x00BE;" >
<!ENTITY frac18  "&#x215B;" >
<!ENTITY frac38  "&#x215C;" >
<!ENTITY frac58  "&#x215D;" >
<!ENTITY frac78  "&#x215E;" >
<!ENTITY frac13  "&#x2153;" >
<!ENTITY frac23  "&#x2154;" >
<!ENTITY frac15  "&#x2155;" >
<!ENTITY frac25  "&#x2156;" >
<!ENTITY frac35  "&#x2157;" >
<!ENTITY frac45  "&#x2158;" >
<!ENTITY frac16  "&#x2159;" >
<!ENTITY frac56  "&#x215A;" >

<!ENTITY mdash  "&#x2014;" >

 ..... lots of others

<!ENTITY uuml    "&#252;" >
<!ENTITY yacute  "&#253;" >
<!ENTITY thorn   "&#254;" >
<!ENTITY yuml    "&#255;" >

]>';

$parseThis = $decl . "<rootname> ..... </rootname>";

This works fine for all the single-byte (European) codes,
but not the wide codes like emdash or frac18.
They seem to be trashed when the character data handler gets them.  They all echo as "?"

There may be a way to make them work, but until I find it,
or a newer release takes care of it, here is a work-around that does work.

2. Rewrite every ampersand as &amp; in the input stream

 $ampXML = str_replace ("&", "&amp;", $sourceXML);

Now the parser will see &amp;foo; instead of &foo;

It does not try to decode it, so wide (two byte) values are not a problem, and no list of names is needed.

When you write that to your output you have &foo;

which is usually fine for the next stage of your process.
www.PhoC.de 20-May-2003 07:39
In some cases it's better to avoid storing data which is not needed. In these cases the function

chop()  ( => Alias of function rtrim() )

could be usefull to prevent data like

"\t"
"\r"
"\o"
"\n"
"\x0B"
" "

to be stored in a array or a string or something like this.

Example: (storing data in a string)
________________
$filename="xyz.xml";

if(!($fp=fopen($filename,"r"))){
   die("Cannot open $filename ");
}

while (!feof($fp))
{
   $data .= chop(fgets($fp, 4096));
}

fclose($fp);
________________

Have a look at the documentation of rtrim() http://www.php.net/manual/en/function.rtrim.php.

Greetz
PhoC
waldo at wh-e dot com 06-Mar-2002 09:52
Here's a way to strip all the spaces between tags in an xml document.

//strip white space between tags
$data=eregi_replace(">"."[[:space:]]+"."<","><",$data);

So this:

<house>
  <garage>
    <car>Waldo</car>
  </garage>
</house>

would be changed to:

<house><garage><car>Waldo</car></garage></house>

It was useful to me. Maybe you too?
ken at positive-edge dot com 29-Jan-2002 08:20
the function handler is called several times when it parses the character data.  It doesn't return the entire string as it suggests.  There are special exceptions that will always force the parser to stop scanning and call the character data handler.  This is when:

- The parser runs into an Entity Declaration, such as &amp; (&) or &apos; (?)
- The parser finishes parsing an entity
- The parser runs into the new-line character (\n)
- The parser runs into a series of tab characters (\t)

And perhaps others.

For instance, if we have this xml content:

<mytag name=?Ken Egervari? title=?Chief Technology Officer?>
    Ken has been Positive Edge&apos;s Chief Technology Officer for 2 years.
</mytag>

The parser will call the character data handler 6 times.  This is what will happen:

1    \n
2    \t
3    Ken has been Positive Edge
4    ?
5    s Chief Technology Officer for 2 years.
6    \n

I hope that helps people out.
mogmios at mlug dot missouri dot edu 24-Oct-2001 04:24
If you want to strip unwanted whitespace in an HTML-like manner then there are two steps.

The first you need to strip consecutive whitespaces from all you input data like this:  $data = eregi_replace ( "[[:space:]]+", " ", $data );

Then in your cdata handler make a check to see if it's blank space. An easy way is like this: if ( trim ( $cdata ) ) { work on cdata }

That should take care of any whitespace issues you might have.
annies at cs dot tu-berlin dot de 03-Aug-2001 10:43
The maximum size of the second parmeter $data seems to be 1024. Is there more character data  in the XML text the handler is called again immediately with the next portion.


Set up default handler

  • « xml_set_character_data_handler
  • xml_set_element_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up default handler

xml_set_default_handler

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

xml_set_default_handler — Set up default handler

Description

xml_set_default_handler(XMLParser $parser, callable $handler): true

Sets the default handler function for the XML parser parser.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
The XML parser calling the handler.
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.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

User Contributed Notes

anoril at anoril dot com 13-Jul-2006 07:54
I have the same issue using two installation of PHP5: on accepts to use the default handler while the other only uses the character_data one.

Maybe a configuration problem...

;) Nonor.
phillip 26-Apr-2005 02:13
it seems to me that in PHP5 the function defined as default-handler (using xml_set_default_handler()) doesen't get passed the cdata anymore:

i.e.:
xml_set_element_handler($this->parser, 'parseSTART', 'parseEND');
xml_set_default_handler($this->parser, 'parseDEFAULT');
function parseSTART() { ... }
function parseEND() { ... }
function parseDEFAULT() { ... }

under PHP5, parseDEFAULT will NOT get passed any cdata, but unter PHP4 it will. at least that's my take on the strange stuff (not) happening after migrating to PHP5.

my solution was to add a xml_set_character_data_handler($parser, 'parseDEFAULT'). it worked for me.


Set up start and end element handlers

  • « xml_set_default_handler
  • xml_set_end_namespace_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • 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

Description

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.

Parameters

parser

The XML parser.

start_handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

start_element_handler(XMLParser $parser, string $name, array $attributes): void
parser
The XML parser calling the handler.
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

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

end_element_handler(XMLParser $parser, string $name): void
parser
The XML parser calling the handler.
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.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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

Description

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.

Caution

This event is not supported under libXML, so a registered handler wouldn't be called.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix)
parser
The XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object. false if no prefix exists.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

See Also

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

Description

xml_set_external_entity_ref_handler(XMLParser $parser, callable $handler): true

Sets the external entity reference handler function for the XML parser parser.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $open_entity_names,
string|false $base,
string $system_id,
string|false $public_id
): bool
parser
The XML parser calling the handler.
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.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.
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 Functions
  • 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

Description

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.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $notation_name,
string|false $base,
string $system_id,
string|false $public_id
): void
parser
The XML parser calling the handler.
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.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Use XML Parser within an object

  • « xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler »
  • PHP Manual
  • XML Parser Functions
  • 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

Description

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.

Parameters

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

Examples

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

The above example will output:

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

Description

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

Caution

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.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $target, string $data): void
parser
The XML parser calling the handler.
target
The processing instruction target.
data
The processing instruction data.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Set up start namespace declaration handler

  • « xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • 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

Description

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.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix, string $uri): void
parser
The XML parser calling the handler.
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.

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

See Also

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

Description

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.

Parameters

parser

The XML parser.

handler

If null or an empty string is passed, the handler is reset to its default state.

If handler is a callable, the callable is set as the handler.

If handler is a string, it can be the name of a method of an object set with xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $entity_name,
string|false $base,
string $system_id,
string|false $public_id,
string|false $notation_name
): void
parser
The XML parser calling the handler.
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()).

Return Values

Always returns true.

Changelog

Version | Description
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


The XMLParser class

(PHP 8)

Introduction

A fully opaque class which replaces xml resources as of PHP 8.0.0.

Class synopsis

final class XMLParser {
}

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • XMLReader — The XMLReader class
    • XMLReader::close — Close the XMLReader input
    • XMLReader::expand — Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute — Get the value of a named attribute
    • XMLReader::getAttributeNo — Get the value of an attribute by index
    • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty — Indicates if specified property has been set
    • XMLReader::isValid — Indicates if the parsed document is valid
    • XMLReader::lookupNamespace — Lookup namespace for a prefix
    • XMLReader::moveToAttribute — Move cursor to a named attribute
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
    • XMLReader::next — Move cursor to next node skipping all subtrees
    • XMLReader::open — Set the URI containing the XML to parse
    • XMLReader::read — Move to next node in document
    • XMLReader::readInnerXml — Retrieve XML from current node
    • XMLReader::readOuterXml — Retrieve XML from current node, including itself
    • XMLReader::readString — Reads the contents of the current node as a string
    • XMLReader::setParserProperty — Set parser options
    • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
    • XMLReader::setSchema — Validate document against XSD
    • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

There are no user contributed notes for this page.


Introduction

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Encoding

It is important to note that internally, libxml uses the UTF-8 encoding and as such, the encoding of the retrieved contents will always be in UTF-8 encoding.

User Contributed Notes

There are no user contributed notes for this page.


Installation

The XMLReader ships with PHP source. This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-xmlreader

User Contributed Notes

Miguel Cruz 11-Jun-2012 01:06
If you are having trouble loading this extension (perhaps with a log message like 'Undefined symbol "dom_node_class_entry"'), make sure that you have xmlreader.so listed AFTER dom.so in php.ini.
alvaro at digdib dot com 02-Jan-2009 02:33
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlreader by default. To enable this option, add the flag xmlreader to your USE variable and recompile php.


The XMLReader class

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

Introduction

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Class synopsis

class XMLReader {
/* Constants */
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;
/* Properties */
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;
/* Methods */
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
}

Properties

attributeCount

The number of attributes on the node

baseURI

The base URI of the node

depth

Depth of the node in the tree, starting at 0

hasAttributes

Indicates if node has attributes

hasValue

Indicates if node has a text value

isDefault

Indicates if attribute is defaulted from DTD

isEmptyElement

Indicates if node is an empty element tag

localName

The local name of the node

name

The qualified name of the node

namespaceURI

The URI of the namespace associated with the node

nodeType

The node type for the node

prefix

The prefix of the namespace associated with the node

value

The text value of the node

xmlLang

The xml:lang scope which the node resides

Predefined Constants

XMLReader Node Types

XMLReader::NONE

No node type

XMLReader::ELEMENT

Start element

XMLReader::ATTRIBUTE

Attribute node

XMLReader::TEXT

Text node

XMLReader::CDATA

CDATA node

XMLReader::ENTITY_REF

Entity Reference node

XMLReader::ENTITY

Entity Declaration node

XMLReader::PI

Processing Instruction node

XMLReader::COMMENT

Comment node

XMLReader::DOC

Document node

XMLReader::DOC_TYPE

Document Type node

XMLReader::DOC_FRAGMENT

Document Fragment node

XMLReader::NOTATION

Notation node

XMLReader::WHITESPACE

Whitespace node

XMLReader::SIGNIFICANT_WHITESPACE

Significant Whitespace node

XMLReader::END_ELEMENT

End Element

XMLReader::END_ENTITY

End Entity

XMLReader::XML_DECLARATION

XML Declaration node

XMLReader Parser Options

XMLReader::LOADDTD

Load DTD but do not validate

XMLReader::DEFAULTATTRS

Load DTD and default attributes but do not validate

XMLReader::VALIDATE

Load DTD and validate while parsing

XMLReader::SUBST_ENTITIES

Substitute entities and expand references

Table of Contents

  • XMLReader::close — Close the XMLReader input
  • XMLReader::expand — Returns a copy of the current node as a DOM object
  • XMLReader::getAttribute — Get the value of a named attribute
  • XMLReader::getAttributeNo — Get the value of an attribute by index
  • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
  • XMLReader::getParserProperty — Indicates if specified property has been set
  • XMLReader::isValid — Indicates if the parsed document is valid
  • XMLReader::lookupNamespace — Lookup namespace for a prefix
  • XMLReader::moveToAttribute — Move cursor to a named attribute
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
  • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
  • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
  • XMLReader::next — Move cursor to next node skipping all subtrees
  • XMLReader::open — Set the URI containing the XML to parse
  • XMLReader::read — Move to next node in document
  • XMLReader::readInnerXml — Retrieve XML from current node
  • XMLReader::readOuterXml — Retrieve XML from current node, including itself
  • XMLReader::readString — Reads the contents of the current node as a string
  • XMLReader::setParserProperty — Set parser options
  • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
  • XMLReader::setSchema — Validate document against XSD
  • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

eef dot vreeland at gmail dot com 10-Aug-2017 05:43
Please discard my previous note; I pressed 'Add Note' too quickly

About (non-)self-closing tags:

 A) <tag></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 B) <tag />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 C) <tag attribute="value"></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

 D) <tag attribute="value" />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

... and always use the '===' operator when testing properties
eef dot vreeland at gmail dot com 10-Aug-2017 05:08
Note that when:

A) <tag></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => true
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

B) <tag />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

C) <tag attribute="value"></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true

D) <tag attribute="value" />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true
Sean Colin Ruiz 08-Jan-2017 03:11
As japos mentioned. Take care how you use isEmptyElement. After you are done looping through the attributes: isEmptyElement will be false.  You can use moveToElement() to move the cursor back to the element and then you can use isEmptyElement like normal again.
dkrnl at yandex dot ru 04-Oct-2013 04:10
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

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

<?php

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

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

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

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

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

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

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

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

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

}
?>
kula_shakerz 03-Apr-2013 02:27
Found this in the IXmlReader docs at msdn but it's also valid for XMLReader in PHP.

You should save the value of $isEmptyElement before processing attributes, or call moveToElement to make $isEmptyElement valid after processing attributes.

$isEmptyElement returns FALSE when XMLReader is positioned on an attribute node, even if attribute's parent element is empty.
Mike De Smet 25-Sep-2012 04:35
For those of you getting xml files that do not contain duplicate elements (in the same element), the following converter converts to arrays with key/value mapping (thus overwriting duplicate elements!):

Note this is untested with attributes although I built in support.

<?php
    function xml2assoc($xml, array &$target = array()) {
        while ($xml->read()) {
            switch ($xml->nodeType) {
                case XMLReader::END_ELEMENT:
                    return $target;
                case XMLReader::ELEMENT:
                    $name = $xml->name;
                    $target[$name] = $xml->hasAttributes ? array() : '';
                    if (!$xml->isEmptyElement) {
                        $target[$name] = array();
                        xml2assoc($xml, $target[$name]);
                    }

                    if ($xml->hasAttributes)
                        while($xml->moveToNextAttribute())
                            $target[$name]['@'.$xml->name] = $xml->value;
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:
                    $target = $xml->value;
            }
        }
        return $target;
    }
?>
casella dot email at google dot mail dot com 22-Sep-2012 03:59
To verify that all nodes are read without error/warning you can use this code:
<?php
$endofxml = false;
$xml_url = "example.xml";
$reader = new XMLReader();
if(!$reader->open($xml_url)){
    print "Error to open XML: $xml_url\n";
} else {
    while ($reader->read()) {
        $firstnode = (!isset($firstnode)) ? $reader->name : $firstnode;
/*
DO SOMETHING
*/
        if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == $firstnode) {
            $endofxml = true;
        }
    }
}
if($endofxml) {
    print "no error found";
} else {
    print "error found";
}
?>

This code is useful to trap $reader->read() error/warning.
lee8oi at gmail dot com 21-Mar-2012 01:54
Sometimes you have an unusual URL that doesn't actually point to an xml file but still returns xml as output (Like the Battlefield Heroes generated syndication urls). Using get_file_contents(url) you can retrieve the xml data from these urls and pass it as a variable for processing as an XML String.

Unfortunately simpleXML or xml DOM cannot process all xml strings. Some have error boxes added to the end of them (such as Battlefield Heroes syndicated news). These boxes cause an end of file sort of error and closes out the script. XMLReader grabs data from these strings without error.
japos dot trash at googlemail dot com 09-Oct-2010 02:17
Take care about how to use XMLReader::$isElementEmpty. I don't know if it is a bug or not, but $isElementEmpty is set for the current context and NOT just for the element. If you move your cursor to an attribute, $isElementEmpty will ALWAYS be false.

<?php
 $xml = new XMLReader();
 $xml->XML('<tag attr="value" />');
 $xml->read();
 var_dump($xml->isEmptyElement);
 $xml->moveToNextAttribute();
 var_dump($xml->isEmptyElement);
?>

will output

(bool) true
(bool) false

So be sure to store $isEmptyElement before moving the cursor.
jart (at) mail.ru 23-Sep-2010 06:59
Guys, I hope this example will help
you can erase prints showing the process-
and it will be a piece of nice code.

<?php
function xml2assoc($xml, $name)
{
    print "<ul>";

    $tree = null;
    print("I'm inside " . $name . "<br>");

    while($xml->read())
    {
        if($xml->nodeType == XMLReader::END_ELEMENT)
        {
            print "</ul>";
            return $tree;
        }

        else if($xml->nodeType == XMLReader::ELEMENT)
        {
            $node = array();

            print("Adding " . $xml->name ."<br>");
            $node['tag'] = $xml->name;

            if($xml->hasAttributes)
            {
                $attributes = array();
                while($xml->moveToNextAttribute())
                {
                    print("Adding attr " . $xml->name ." = " . $xml->value . "<br>");
                    $attributes[$xml->name] = $xml->value;
                }
                $node['attr'] = $attributes;
            }

            if(!$xml->isEmptyElement)
            {
                $childs = xml2assoc($xml, $node['tag']);
                $node['childs'] = $childs;
            }

            print($node['tag'] . " added <br>");
            $tree[] = $node;
        }

        else if($xml->nodeType == XMLReader::TEXT)
        {
            $node = array();
            $node['text'] = $xml->value;
            $tree[] = $node;
            print "text added = " . $node['text'] . "<br>";
        }
    }

    print "returning " . count($tree) . " childs<br>";
    print "</ul>";

    return $tree;
}

echo "<PRE>";

$xml = new XMLReader();
$xml->open('test.xml');
$assoc = xml2assoc($xml, "root");
$xml->close();

print_r($assoc);
echo "</PRE>";

?>

It reads this xml:

<test>
    <hallo volume="loud"> me <br/> lala </hallo>
    <hallo> me </hallo>
</test>
jnettles at inccrra dot org 02-Oct-2009 09:51
Just in case someone is confused, if you're wanting to simply pass a string of XML instead of an entire file, you would do this.

<?php
$foo = new XMLReader();
$foo->xml($STRING);
?>

.... where $STRING holds your XML. You cannot pass it like $foo = $STRING or $foo->xml = $STRING.
james dot ellis at example dot com 25-Mar-2009 03:16
The "XML2Assoc" functions noted here should be used with caution... basically they are duplicating the functionality already present in SimpleXML. They may work but they won't scale.

Their are two main uses cases for parsing XML, each suited to either XMLReader or SimpleXML.

1. SimpleXML is an excellent tool for easy access to an XML document tree using native PHP data types. It starts to flounder with massive (> 50M or so) XML documents, as it reads the entire document into memory before it can be processed. SimpleXML will just laugh at you then die when your server runs out of memory (or it will cause a load spike).

2. Aside from the reasoning behind massive XML documents, if you have to deal with massive XML documents, use XMLReader to process them. Don't try and gather an entire XML document into a PHP data structure using XMLReader and a PHP xml2assoc() function, you are reinventing the SimpleXML wheel.
When parsing massive XML documents using XMLReader, gather the data you need to perform an operation then perform it before skipping to the next node. Do not build massive data structures from a massive XML document, your server (and it's admins) will not like you.
PxL 23-Jan-2009 03:36
A basic parser

<?php
function xml2assoc($xml) {
    $arr = array();
    if (!preg_match_all('|\<\s*?(\w+).*?\>(.*)\<\/\s*\\1.*?\>|s', $xml, $m)) return $xml;
    if (is_array($m[1]))
        for ($i = 0;$i < sizeof($m[1]); $i++) $arr[$m[1][$i]] = xml2assoc($m[2][$i]);
    else $arr[$m[1]] = xml2assoc($m[2]);

    return $arr;
}
?>
boukeversteegh at gmail dot com 18-Jan-2009 02:06
XML to ASSOCIATIVE ARRAY

Improved algorithm based on Sergey Aikinkulov's. The problem was that it would overwrite nodes if they had the same tag name. Because of that <a><b/><b/><a> would be read as if <a><b/><a/>. This algorithm handles it better and outputs an easy to understand array:

<?php
function xml2assoc($xml) {
    $tree = null;
    while($xml->read())
        switch ($xml->nodeType) {
            case XMLReader::END_ELEMENT: return $tree;
            case XMLReader::ELEMENT:
                $node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
                if($xml->hasAttributes)
                    while($xml->moveToNextAttribute())
                        $node['attributes'][$xml->name] = $xml->value;
                $tree[] = $node;
            break;
            case XMLReader::TEXT:
            case XMLReader::CDATA:
                $tree .= $xml->value;
        }
    return $tree;
}

?>

Usage:

myxml.xml:
------
<PERSON>
    <NAME>John</NAME>
    <PHONE type="home">555-555-555</PHONE>
</PERSON>
----

<?
    $xml = new XMLReader();
    $xml->open('myxml.xml');
    $assoc = xml2assoc($xml);
    $xml->close();
    print_r($assoc);
?>

Outputs:
Array
(
    [0] => Array
        (
            [tag] => PERSON
            [value] => Array
                (
                    [0] => Array
                        (
                            [tag] => NAME
                            [value] => John
                        )

                    [1] => Array
                        (
                            [tag] => PHONE
                            [value] => 555-555-555
                            [attributes] => Array
                                (
                                    [type] => home
                                )

                        )

                )

        )

)

For reasons that have to do with recursion, it returns an array with the ROOT xml node as the first childNode, rather than to return only the ROOT node.
andrei_antal at yahoo dot com 08-Jan-2009 08:25
<?php
//Pull certain elements
 $reader = new XMLReader();
  $reader->open($xmlfile);
while ($reader->read()) {
 switch ($reader->nodeType) {
   case (XMLREADER::ELEMENT):

if ($reader->name == "Code")
     {
       $reader->read();
       $code = trim($reader->value);
       echo "$code\n";
       break;
     }

 if ($reader->name == "Name")
     {
       $reader->read();
       $customername = trim( $reader->value );
       echo "$name\n";
       break;
     }

 if ($reader->name == "Camp")
    {
      $camp = trim($reader->getAttribute("ID"));
       echo "$camp\n";
      break;
    }
  }
}
?>
godseth at o2 dot pl 28-Nov-2008 02:34
Thanks rein_baarsma33 AT hotmail DOT com for bugfixes.

This is my new child of XML parsing method  based on my and yours modification.

XML2ASSOC Is a complete solution for parsing ordinary XML

<?php
/**
 * XML2Assoc Class to creating
 * PHP Assoc Array from XML File
 *
 * @author godseth (AT) o2.pl & rein_baarsma33 (AT) hotmail.com (Bugfixes in parseXml Method)
 * @uses XMLReader
 *
 */

class Xml2Assoc {

    /**
     * Optimization Enabled / Disabled
     *
     * @var bool
     */
    protected $bOptimize = false;

    /**
     * Method for loading XML Data from String
     *
     * @param string $sXml
     * @param bool $bOptimize
     */

    public function parseString( $sXml , $bOptimize = false) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {

            // Set String Containing XML data
            $oXml->XML($sXml);

            // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * Method for loading Xml Data from file
     *
     * @param string $sXmlFilePath
     * @param bool $bOptimize
     */
    public function parseFile( $sXmlFilePath , $bOptimize = false ) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {
            // Open XML file
            $oXml->open($sXmlFilePath);

            // // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage(). ' | Try open file: '.$sXmlFilePath;
        }
    }

    /**
     * XML Parser
     *
     * @param XMLReader $oXml
     * @return array
     */
    protected function parseXml( XMLReader $oXml ) {

        $aAssocXML = null;
        $iDc = -1;

        while($oXml->read()){
            switch ($oXml->nodeType) {

                case XMLReader::END_ELEMENT:

                    if ($this->bOptimize) {
                        $this->optXml($aAssocXML);
                    }
                    return $aAssocXML;

                case XMLReader::ELEMENT:

                    if(!isset($aAssocXML[$oXml->name])) {
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name] = '';
                            } else {
                                $aAssocXML[$oXml->name] = $this->parseXML($oXml);
                            }
                        }
                    } elseif (is_array($aAssocXML[$oXml->name])) {
                        if (!isset($aAssocXML[$oXml->name][0]))
                        {
                            $temp = $aAssocXML[$oXml->name];
                            foreach ($temp as $sKey=>$sValue)
                            unset($aAssocXML[$oXml->name][$sKey]);
                            $aAssocXML[$oXml->name][] = $temp;
                        }

                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    } else {
                        $mOldVar = $aAssocXML[$oXml->name];
                        $aAssocXML[$oXml->name] = array($mOldVar);
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    }

                    if($oXml->hasAttributes) {
                        $mElement =& $aAssocXML[$oXml->name][count($aAssocXML[$oXml->name]) - 1];
                        while($oXml->moveToNextAttribute()) {
                            $mElement[$oXml->name] = $oXml->value;
                        }
                    }
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:

                    $aAssocXML[++$iDc] = $oXml->value;

            }
        }

        return $aAssocXML;
    }

    /**
     * Method to optimize assoc tree.
     * ( Deleting 0 index when element
     *  have one attribute / value )
     *
     * @param array $mData
     */
    public function optXml(&$mData) {
        if (is_array($mData)) {
            if (isset($mData[0]) && count($mData) == 1 ) {
                $mData = $mData[0];
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        $this->optXml($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    $this->optXml($aSub);
                }
            }
        }
    }

}

?>

[EDIT BY danbrown AT php DOT net:  Fixes were also provided by "Alex" and (qdog AT qview DOT org) in user notes on this page (since removed).]
Sergey Aikinkulov 19-Jun-2008 03:51
Next version xml2assoc with some improve fixes:
 - no doubled data
 - no buffer arrays

<?php
/*
    Read XML structure to associative array
    --
    Using:
    $xml = new XMLReader();
    $xml->open([XML file]);
    $assoc = xml2assoc($xml);
    $xml->close();
*/
    function xml2assoc($xml) {
      $assoc = null;
      while($xml->read()){
        switch ($xml->nodeType) {
          case XMLReader::END_ELEMENT: return $assoc;
          case XMLReader::ELEMENT:
            $assoc[$xml->name][] = array('value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
            if($xml->hasAttributes){
              $el =& $assoc[$xml->name][count($assoc[$xml->name]) - 1];
              while($xml->moveToNextAttribute()) $el['attributes'][$xml->name] = $xml->value;
            }
            break;
          case XMLReader::TEXT:
          case XMLReader::CDATA: $assoc .= $xml->value;
        }
      }
      return $assoc;
    }
?>
desk_ocean at msn dot com 16-Mar-2008 10:03
make some modify from Sergey Aikinkulov's note

<?php
function xml2assoc(&$xml){
    $assoc = NULL;
    $n = 0;
    while($xml->read()){
        if($xml->nodeType == XMLReader::END_ELEMENT) break;
        if($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = xml2assoc($xml);
            $n++;
        }
        else if($xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = "";
            $n++;
        }
        else if($xml->nodeType == XMLReader::TEXT) $assoc = $xml->value;
    }
    return $assoc;
}
?>

add else if($xml->isEmptyElement)
may be some xml has emptyelement
itari 15-Feb-2008 08:30
<?php
function parseXML($node,$seq,$path) {
global $oldpath;
    if (!$node->read())
      return;
    if ($node->nodeType != 15) {
      print '<br/>'.$node->depth;
      print '-'.$seq++;
      print '  '.$path.'/'.($node->nodeType==3?'text() = ':$node->name);
      print $node->value;
      if ($node->hasAttributes) {
        print ' [hasAttributes: ';
        while ($node->moveToNextAttribute()) print '@'.$node->name.' = '.$node->value.' ';
        print ']';
        }
      if ($node->nodeType == 1) {
        $oldpath=$path;
        $path.='/'.$node->name;
        }
      parseXML($node,$seq,$path);
      }
    else parseXML($node,$seq,$oldpath);
}

$source = "<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>";
$xml = new XMLReader();
$xml->XML($source);
print htmlspecialchars($source).'<br/>';
parseXML($xml,0,'');
?>

Output:

<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>

0-0 /tag1
1-1 /tag1/text() = this
1-2 /tag1/tag2 [hasAttributes: @id = 4 @name = foo ]
2-3 /tag1/text() = is
1-4 /text() = a
1-5 /tag2 [hasAttributes: @id = 5 ]
2-6 /text() = common
1-7 /text() = record
orion at ftf-hq dot dk 15-Feb-2006 04:50
Some more documentation (i.e. examples) would be nice :-)

This is how I read some mysql parameters in an xml file:

<?php
    $xml = new XMLReader();
    $xml->open("config.xml");
    $xml->setParserProperty(2,true); // This seems a little unclear to me - but it worked :)

    while ($xml->read()) {
        switch ($xml->name) {
        case "mysql_host":
            $xml->read();
            $conf["mysql_host"] = $xml->value;
            $xml->read();
            break;
        case "mysql_username":
            $xml->read();
            $conf["mysql_user"] = $xml->value;
            $xml->read();
            break;
        case "mysql_password":
            $xml->read();
            $conf["mysql_pass"] = $xml->value;
            $xml->read();
            break;
        case "mysql_database":
            $xml->read();
            $conf["mysql_db"] = $xml->value;
            $xml->read();
            break;
        }
    }

    $xml->close();
?>

The XML file used:
<?xml version='1.0'?>
<MySQL_INIT>
   <mysql_host>localhost</mysql_host>
   <mysql_database>db_database</mysql_database>
   <mysql_username>root</mysql_username>
   <mysql_password>password</mysql_password>
</MySQL_INIT>


Close the XMLReader input

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Close the XMLReader input

XMLReader::close

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

XMLReader::close — Close the XMLReader input

Description

public XMLReader::close(): true

Closes the input the XMLReader object is currently parsing.

Parameters

This function has no parameters.

Return Values

Always returns true.

See Also

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::xml() - Set the data containing the XML to parse

User Contributed Notes

There are no user contributed notes for this page.


Returns a copy of the current node as a DOM object

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Returns a copy of the current node as a DOM object

XMLReader::expand

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

XMLReader::expand — Returns a copy of the current node as a DOM object

Description

public XMLReader::expand(?DOMNode $baseNode = null): DOMNode|false

This method copies the current node and returns the appropriate DOM object.

Parameters

baseNode

A DOMNode defining the target DOMDocument for the created DOM object.

Return Values

The resulting DOMNode or false on error.

User Contributed Notes

Sbastien 02-Jan-2022 01:29
XMLReader::expand() expands the current subtree to DOM. SimpleXML is good too. To avoid a warning like "Imported Node must have associated Document" when using simplexml_import_dom(), we can do :

<?php

// Huge XML compressed file
$xml = XMLReader::open('compress.zlib:///path/to/my-data.xml.gz');

// Targeting a tiny subtree
while ($xml->name !== 'my-targeted-element') {
    $xml->read();
}

// The trick is here...
// Subtree is expanded in an empty document...
$dom = $xml->expand(new DOMDocument());

// ... which can be imported by SimpleXML
$sx = simplexml_import_dom($dom);

// We can now process our tiny subtree with SimpleXML $sx


Get the value of a named attribute

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Get the value of a named attribute

XMLReader::getAttribute

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

XMLReader::getAttribute — Get the value of a named attribute

Description

public XMLReader::getAttribute(string $name): ?string

Returns the value of a named attribute or null if the attribute does not exist or not positioned on an element node.

Parameters

name

The name of the attribute.

Return Values

The value of the attribute, or null if no attribute with the given name is found or not positioned on an element node.

Changelog

Version | Description
8.0.0 | This function can no longer return false.

See Also

  • XMLReader::getAttributeNo() - Get the value of an attribute by index
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

sven at e7o dot de 08-Nov-2023 02:44
To get all attributes and their names, use something like this:

<?php
function getAttributes($reader)
{
    $attributes = [];
    for ($i = 0; $i < $reader->attributeCount; $i++) {
        $reader->moveToAttributeNo($i);
        $attributes[$reader->name] = $reader->value;
    }
    return $attributes;
}
?>
Anonymous 16-Feb-2011 09:02
Or use XMLReader::ELEMENT and XMLReader::END_ELEMENT rather than the numbers 1 and 15.
Gabi 02-Jul-2007 08:15
might be obvious, but not to everyone ;-) ... when reading attributes from a node that has sub-nodes (and creating an output from this node), the output will be issued twice, once on the <ELEMENT> tag and once on the end tag </ELEMENT>. To avoid this, you can test on which part of the node you are using the property nodeType.
It'll be 1 for the element, 15 for the end element.


Get the value of an attribute by index

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by index

XMLReader::getAttributeNo

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

XMLReader::getAttributeNo — Get the value of an attribute by index

Description

public XMLReader::getAttributeNo(int $index): ?string

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Parameters

index

The position of the attribute.

Return Values

The value of the attribute, or null if no attribute exists at index or is not positioned on the element.

See Also

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

There are no user contributed notes for this page.


Get the value of an attribute by localname and URI

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by localname and URI

XMLReader::getAttributeNs

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

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

Description

public XMLReader::getAttributeNs(string $name, string $namespace): ?string

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Parameters

name

The local name.

namespace

The namespace URI.

Return Values

The value of the attribute, or null if no attribute with the given name and namespace is found or not positioned of element.

Changelog

Version | Description
8.0.0 | This function can no longer return false.

See Also

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNo() - Get the value of an attribute by index

User Contributed Notes

There are no user contributed notes for this page.


Indicates if specified property has been set

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Indicates if specified property has been set

XMLReader::getParserProperty

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

XMLReader::getParserProperty — Indicates if specified property has been set

Description

public XMLReader::getParserProperty(int $property): bool

Indicates if specified property has been set.

Parameters

property

One of the parser option constants.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::setParserProperty() - Set parser options

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the parsed document is valid

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Indicates if the parsed document is valid

XMLReader::isValid

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

XMLReader::isValid — Indicates if the parsed document is valid

Description

public XMLReader::isValid(): bool

Returns a boolean indicating if the document being parsed is currently valid.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Notes

Note: This checks the current node, not the entire document.

See Also

  • XMLReader::setParserProperty() - Set parser options
  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD

User Contributed Notes

me at lubu dot ch 31-May-2022 09:54
Be aware that $xml->isValid() will return validity only for currently active node, so you have to loop trough the nodes.

Here is a example how to validate a entire XML file against a XSD schema:

<?php

$xmlReader = new \XMLReader();
$xmlReader->open('./example.xml');
$xmlReader->setParserProperty(\XMLReader::VALIDATE, true);
$xmlReader->setSchema('./schema.xsd');

\libxml_use_internal_errors(true);

$msgs = [];

while ($xmlReader->read()) {
    if (!$xmlReader->isValid()) {
        $err = \libxml_get_last_error();
        if ($err && $err instanceof \libXMLError) {
            $msgs[] = \trim($err->message) . ' on line ' . $err->line;
        }
    }
}

if ($msgs) {
    throw new \Exception("XML schema validation errors:\n - " . implode("\n - ", array_unique($msgs)));
}
?>
zubin at trattonuovo dot com 20-Jan-2010 03:00
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net 31-Dec-2008 03:27
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
anzenews at volja dot net 22-Jan-2008 10:50
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).


Lookup namespace for a prefix

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Lookup namespace for a prefix

XMLReader::lookupNamespace

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

XMLReader::lookupNamespace — Lookup namespace for a prefix

Description

public XMLReader::lookupNamespace(string $prefix): ?string

Lookup in scope namespace for a given prefix.

Parameters

prefix

String containing the prefix.

Return Values

The value of the namespace, or null if no namespace exists.

Changelog

Version | Description
8.0.0 | This function can no longer return false.

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttribute

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

XMLReader::moveToAttribute — Move cursor to a named attribute

Description

public XMLReader::moveToAttribute(string $name): bool

Positions cursor on the named attribute.

Parameters

name

The name of the attribute.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to an attribute by index

  • « XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs »
  • PHP Manual
  • XMLReader
  • Move cursor to an attribute by index

XMLReader::moveToAttributeNo

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

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

Description

public XMLReader::moveToAttributeNo(int $index): bool

Positions cursor on attribute based on its position.

Parameters

index

The position of the attribute.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • « XMLReader::moveToAttributeNo
  • XMLReader::moveToElement »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttributeNs

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

XMLReader::moveToAttributeNs — Move cursor to a named attribute

Description

public XMLReader::moveToAttributeNs(string $name, string $namespace): bool

Positions cursor on the named attribute in specified namespace.

Parameters

name

The local name.

namespace

The namespace URI.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the parent Element of current Attribute

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the parent Element of current Attribute

XMLReader::moveToElement

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

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

Description

public XMLReader::moveToElement(): bool

Moves cursor to the parent Element of current Attribute.

Parameters

This function has no parameters.

Return Values

Returns true if successful and false if it fails or not positioned on Attribute when this method is called.

See Also

  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

Sean Colin Ruiz 08-Jan-2017 08:54
On an element like this: <self_closing attribute="1" /> isEmptyElement will return FALSE after you have iterated through the attributes.  So you need to use implicitly call moveToElement(), in order to move the cursor back to the parent element and use isEmptyElement again.


Position cursor on the first Attribute

  • « XMLReader::moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the first Attribute

XMLReader::moveToFirstAttribute

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

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

Description

public XMLReader::moveToFirstAttribute(): bool

Moves cursor to the first Attribute.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the next Attribute

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Position cursor on the next Attribute

XMLReader::moveToNextAttribute

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

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

Description

public XMLReader::moveToNextAttribute(): bool

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to next node skipping all subtrees

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Move cursor to next node skipping all subtrees

XMLReader::next

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

XMLReader::next — Move cursor to next node skipping all subtrees

Description

public XMLReader::next(?string $name = null): bool

Positions cursor on the next node skipping all subtrees. If no such node exists, the cursor is moved to the end of the document.

Parameters

name

The name of the next node to move to.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | name is nullable now.

See Also

  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute
  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute

User Contributed Notes

Quiet Noise 13-Apr-2019 01:39
next() without parameters will bring you to the next sibling node on the same depth as the depth where the current cursor is.
Examples:
1. If you are on an opening ELEMENT node next() will bring you to the new line node next to the closing tag of that element (i.e. if you have each tag in separate line) or it will bring you to the opening tag of next node on the same depth.
2. If you are on a TEXT node next() will bring you to the opening tag if there is one next to it.

If there are no more nodes on the given depth next() will bring you to the closing tag (END_ELEMENT) of the wrapping parent.
ppp dot BOTSNEEDNOTAPPLY at salesfloor dot net 08-Sep-2015 09:48
This method appears to follow these rules:

 - if $localName names a sibling node, the cursor is moved to that node;
 - if $localName names an ancestor node, the cursor is moved to the end of that node;
 - if $localName names a node that is a sibling of any of the current node's ancestors, the cursor is moved to that node;
 - otherwise the cursor is moved outside the document.

Note especially that this method never moves the cursor to child nodes.

For example, given this XML document

<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>

going from <root id="root"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "aaa" places the cursor on <aaa id="3">;
going from <bbb id="1.1"> to "bbb" places the cursor on <bbb id="1.2">;
going from <bbb id="1.2"> to "bbb" places the cursor outside the document;
going from <bbb id="1.1"> to "ddd" places the cursor outside the document;
going from <bbb id="1.1"> to "aaa" places the cursor on </aaa>;
going from <bbb id="1.1"> to "ccc" places the cursor on <ccc id="2">;
going from <bbb id="1.1"> to "nonsuch" places the cursor outside the document;
going from <bbb id="1.1"> to "root" places the cursor on </root>;
going from <ddd id="3.1"> to "aaa" places the cursor on <aaa id="3.2">;
going from <ddd id="3.1"> to "eee" places the cursor outside the document;

Try it yourself:

<?php

$document = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>
XML;

$filename = "/tmp/xmlreader.php.xml";
file_put_contents($filename, $document);

echo "given this XML document\n\n$document\n\n";

showNext("root", "bbb");
showNext("1", "bbb");
showNext("1", "aaa");
showNext("1.1", "bbb");
showNext("1.2", "bbb");
showNext("1.1", "ddd");
showNext("1.1", "aaa");
showNext("1.1", "ccc");
showNext("1.1", "nonsuch");
showNext("1.1", "root");
showNext("3.1", "aaa");
showNext("3.1", "eee");

function showNext($from, $to) {
  global $filename;

  $xml = new \XmlReader();
  $xml->open("file://$filename");
  while ($xml->read()) {
    if ($xml->nodeType === \XmlReader::ELEMENT) {
      if ($xml->getAttribute("id") == $from) {
        echo "going from <$xml->name id=\"$from\">";
        break;
      }
    }
  }

  $xml->next($to);
  $destination = "";
  if($xml->nodeType === \XmlReader::NONE) {
    if(!$xml->read()) {
      $destination = "outside the document";
    }
  }

  if(!$destination) {
    if ($xml->nodeType === \XmlReader::END_ELEMENT) {
      $destination = "on </$xml->name>";
    } else if ($xml->nodeType === \XmlReader::ELEMENT) {
      $destination = "on <$xml->name id=\"" . $xml->getAttribute("id") . "\">";
    }
  }

  echo " to \"$to\" places the cursor $destination;\n";

  $xml->close();
}
?>
gholson19 at gmail dot com 13-May-2015 09:21
To skip over deletion nodes in the xml extracted from a word document, do something like this:

if ($paragraph->nodeType == XMLREADER::ELEMENT && $paragraph->name === 'w:del'){$paragraph->next();}


Set the URI containing the XML to parse

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • Set the URI containing the XML to parse

XMLReader::open

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

XMLReader::open — Set the URI containing the XML to parse

Description

public static XMLReader::open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader

Set the URI containing the XML document to be parsed.

Parameters

uri

URI pointing to the document.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

Return Values

Returns true on success or false on failure. If called statically, returns an XMLReader or false on failure.

Errors/Exceptions

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Changelog

Version | Description
8.0.0 | XMLReader::open() is now declared as static method, but can still be called on an XMLReader instance.

See Also

  • XMLReader::xml() - Set the data containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

den at nurfuerspam dot de 29-Apr-2017 10:08
If you like to read the XML from HTTP whit a POST request, you can use libxml_set_streams_context.
Example:

<?php

$param = array('http' => array(
    'method' => 'POST',
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query(array(
        'post_param1' => 'value1',
        'post_param2' => 'value2',
    )),
));
libxml_set_streams_context(stream_context_create($param));
$reader = XMLReader::open('https://example.com/get.php?get_param=value3');

?>
dave at sophoservices dot com 02-Dec-2016 07:43
When using the XmlReader to read local XML files, remember it the open function requests a URI. Add 'file://' to the front of the FULL path to the XML. Otherwise you may get:

PHP Warning:  XMLReader::open(): Unable to open source data in ...
mood(_a_)twolate.com 14-Oct-2016 11:03
For some reasons, the open() method keep throwing me this error :

PHP Warning:  XMLReader::open(): Unable to open source data in /var/www/nota/ethamap/fat_xml.php

It doesn't make sense as the xml file target hosted on my server is perfectly reachable. Adding this line before invoking open() fixed it :

libxml_disable_entity_loader(false);

Please view https://bugs.php.net/bug.php?id=62577
It is somehow related.
alvaro at demogracia dot com 14-Nov-2014 12:35
XML can optionally declare its own encoding:

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

You can use the $encoding parameter to provide this information (if missing) or override it (if wrong).

Output is always UTF-8 (that's how libxml works).
crungmungus at gmail dot com 15-Sep-2008 05:11
Windows users remember to enable php_openssl.dll in your php.ini if you want to be able to use this function (and others) with a HTTPS URL.


Move to next node in document

  • « XMLReader::open
  • XMLReader::readInnerXml »
  • PHP Manual
  • XMLReader
  • Move to next node in document

XMLReader::read

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

XMLReader::read — Move to next node in document

Description

public XMLReader::read(): bool

Moves cursor to the next node in the document.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::next() - Move cursor to next node skipping all subtrees

User Contributed Notes

peter at 3xe dot co dot uk 13-Oct-2016 12:08
Another approach to the 'also reads closing tags' gotcha:

<?php
$reader = new XMLReader();
$reader->open('users.xml');

while ($reader->read()) {
  if ($reader->nodeType == XMLReader::END_ELEMENT) {
    continue; //skips the rest of the code in this iteration
  }
  //do something with desired node type
  if($reader->name == 'user') {
    //...
  }
}
?>
Anonymous 20-Mar-2015 09:49
> I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.

I just use:

$reader->close();
$reader->open($url);

to reset the pointer.
ecziegler at gmail 29-Jan-2014 12:27
If like myself you have been turning the interwebz upside down looking for a solution for this issue:
PHP Warning:  XMLReader::read(): /tmp/xml_feed.xml:4183934: parser error : Input is not proper UTF-8, indicate encoding !

For some reason, this warning breaks the execution - is it a fatal error in disguise?

After days of frustration I found it!!!!
tidy -xml -o output.xml -utf8 -f error.log input.xml

You can invoque tidy using exec, It takes several seconds to convert a 250Mb feed, but it worthy the time.

In my case the issue was with latin1 charset, and for some reason I had to pass the xml through tidy 2 times - first time around creates new errors, second time it fixes everything.

I know invalid xml should be fixed by xml creators, but it works differently in the real world.
Nate 27-Jun-2011 10:49
It is interesting to note that this function will stop on closing tags as well.  I have an XML document similar to the following:

<root>
  <columns>
    <column>columnX</column>
    <column>columnY</column>
  </columns>
  <table>
    <row>
      <columnX>38</columnX>
      <columnY>50</columnY>
    </row>
    <row>
      <columnX>82</columnY>
      <columnY>28</columnY>
    </row>
    ...
  </table>
</root>

I need to parse the <columns> object to know what attributes to check for from each <row> node.  Therefore I was doing the following:

<?php
while ($xml->read()) {
  if ($xml->name === 'column') {
   //parse column node to into $columns array
  }
  elseif ($xml->name === 'row') {
    //parse row node, using constructed $columns array
  }
}
?>

This kind of worked in that I ended up with an array of all the data I wanted, but the array I constructed was twice as large as I expected and every other entry was empty.  Took me a while to debug, but finally figured out that checking <?php $xml->name === 'row' ?> matches both <row> and </row>, so the check should really be something more like:

<?php

if ($xml->name === 'row' && $xml->nodeType == XMLReader::ELEMENT) {
  // parse row node
}

?>

I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.
andy at siliconrockstar dot com 16-May-2011 01:01
A very simple way to avoid typing $reader->read() multiple times when you want to skip some nodes:

<?php
class smartXMLReader extends XMLReader {
    public function readTimes($count) {
        $i = 0;
        while($i < $count){
            $this->read();
            $i++;
        }
    }
}
?>

Using this smartXMLReader,

<?php
$reader->readTimes(3);
?>

is equivalent to

<?php
$reader->read();
$reader->read();
$reader->read();
?>

Makes getting around in your XML document a bit easier :)
jirka at kosek dot cz 08-Feb-2006 01:01
libxml2 contains much more useful method readString() that will read and return whole text content of element. You can call it after receiving start tag (XMLReader::ELEMENT). You can use this PHP code to emulate this method until PHP will directly call underlying libxml2 implementation.

<?php
class XMLReader2 extends XMLReader
{
  function readString()
  {
        $depth = 1;
        $text = "";

        while ($this->read() && $depth != 0)
        {
            if (in_array($this->nodeType, array(XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE, XMLReader::SIGNIFICANT_WHITESPACE)))
                $text .= $this->value;
            if ($this->nodeType == XMLReader::ELEMENT) $depth++;
            if ($this->nodeType == XMLReader::END_ELEMENT) $depth--;
        }
        return $text;
    }
}
?>

Just use XMLReader2 instead of XMLReader.


Retrieve XML from current node

  • « XMLReader::read
  • XMLReader::readOuterXml »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node

XMLReader::readInnerXml

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

XMLReader::readInnerXml — Retrieve XML from current node

Description

public XMLReader::readInnerXml(): string

Reads the contents of the current node, including child nodes and markup.

Parameters

This function has no parameters.

Return Values

Returns the contents of the current node as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

There are no user contributed notes for this page.


Retrieve XML from current node, including itself

  • « XMLReader::readInnerXml
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node, including itself

XMLReader::readOuterXml

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

XMLReader::readOuterXml — Retrieve XML from current node, including itself

Description

public XMLReader::readOuterXml(): string

Reads the contents of the current node, including the node itself.

Parameters

This function has no parameters.

Return Values

Returns the contents of current node, including itself, as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

ralf dot horlebein at web dot de 21-Jul-2014 10:57
Please note that empty tags like <span></span> will be automatically converted to the short notation <span />.  This could cause trouble in some cases.
simon at avalon dot net dot nz 16-Mar-2011 04:35
Be aware that when you extract a piece of XML from a larger XML document using the readOuterXML() function, it tries to determine the namespaces (as defined in the original XML document) that apply to the new piece, and inserts them into the appropriate tags as xmlns attributes. This can be disconcerting, but it should be a benign alteration in most cases, and I understand that it causes the new chunk of XML to be correctly formatted so it is valid in it's own right.

As far as I'm aware it's not possible to change this behaviour.


Reads the contents of the current node as a string

  • « XMLReader::readOuterXml
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Reads the contents of the current node as a string

XMLReader::readString

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

XMLReader::readString — Reads the contents of the current node as a string

Description

public XMLReader::readString(): string

Reads the contents of the current node as a string.

Parameters

This function has no parameters.

Return Values

Returns the content of the current node as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

alexander_behling at web dot de 25-Jan-2018 03:37
Important:
When using it use -> instead of ::.
You have to use :: only on static functions and then you have not to create a class object.
Lea Hayes 07-Jun-2011 01:51
I would like to reiterate that this does not work when compiled with versions of libxml lower than 20620. I found that it just presents a blank page.

<?php $string = $reader->readString(); ?>

I worked around this issue by adding the following helper function:

<?php
function read_string($reader) {
    $node = $reader->expand();
    return $node->textContent;
}
?>

And then using:

<?php $string = read_string($reader); ?>
Michael Rusch 18-May-2009 10:27
For those who, like me, are having trouble figuring out the difference between getString() an getInnerXML(), the difference is that getString() does NOT include markup.  So, for:

<foo>bar<baz>Hello, world!</baz></foo>

getString() on the <foo> node would return

bar Hello, world!

whereas getInnerXML() would return

bar<baz>Hello, world!</baz>


Set parser options

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Set parser options

XMLReader::setParserProperty

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

XMLReader::setParserProperty — Set parser options

Description

public XMLReader::setParserProperty(int $property, bool $value): bool

Set parser options. The options must be set after
XMLReader::open() or
XMLReader::xml() are called and before
the first XMLReader::read() call.

Parameters

property

One of the parser option constants.

value

If set to true the option will be enabled otherwise will be disabled.

Return Values

Returns true on success or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the filename or URI for a RelaxNG Schema

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Set the filename or URI for a RelaxNG Schema

XMLReader::setRelaxNGSchema

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

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

Description

public XMLReader::setRelaxNGSchema(?string $filename): bool

Set the filename or URI for the RelaxNG Schema to use for validation.

Parameters

filename

filename or URI pointing to a RelaxNG Schema.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:40
Make sure to load your data prior to calling ->setRelaxNGSchema() otherwise you will get an error.

<?php
$xml_reader = new XMLReader();
$xml_reader->setRelaxNGSchema($rng_schema);
$xml_reader->xml($xml_data);
?>
Above code generates the following warning: "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

whereas the following does not generate a warning:
<?php
$xml_reader = new XMLReader();
$xml_reader->xml($xml_data); // or $xml_reader->xml($xml_file);
$xml_reader->setRelaxNGSchema($rng_schema);
?>

cf. http://bugs.php.net/bug.php?id=46978


Set the data containing a RelaxNG Schema

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Set the data containing a RelaxNG Schema

XMLReader::setRelaxNGSchemaSource

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

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

Description

public XMLReader::setRelaxNGSchemaSource(?string $source): bool

Set the data containing a RelaxNG Schema to use for validation.

Parameters

source

String containing the RelaxNG Schema.

Return Values

Returns true on success or false on failure.

See Also

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:43
If you get the following warning message when calling ->setRelaxNGSchemaSource(): "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

Make sure to load data using XMLReader::open() or XMLReader::xml() prior to calling XMLReader::setRelaxNGSchemaSource().

Cf. comment on XMLReader::setRelaxNGSchema for more details.
anzenews at volja dot net 21-Jan-2008 12:18
This function and setRelaxNGSchema() seem picky about when they are called - right after the call to open(). For example:

<?php
  $schema="/path/to/schema.rng";
  $xmlfile="/path/to/xml.xml";

  $xml = new XMLReader();
  $xml->open($xmlfile);
  $xml->setRelaxNGSchemaSource(file_get_contents($schema));

  while ($xml->read()) {
   // ...
  }

  $xml->close();
?>


Validate document against XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Validate document against XSD

XMLReader::setSchema

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

XMLReader::setSchema — Validate document against XSD

Description

public XMLReader::setSchema(?string $filename): bool

Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read().

Parameters

filename

The filename of the XSD schema.

Return Values

Returns true on success or false on failure.

Errors/Exceptions

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

There are no user contributed notes for this page.


Set the data containing the XML to parse

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Set the data containing the XML to parse

XMLReader::XML

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

XMLReader::XML — Set the data containing the XML to parse

Description

public static XMLReader::XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader

Set the data containing the XML to parse.

Parameters

source

String containing the XML to be parsed.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

Return Values

Returns true on success or false on failure. If called statically, returns an XMLReader or false on failure.

Errors/Exceptions

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Changelog

Version | Description
8.0.0 | XMLReader::XML() is now declared as static method, but can still be called on an XMLReader instance.

See Also

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Creating a simple XML document
    • Working with XML namespaces
    • Working with the OO API
  • XMLWriter — The XMLWriter class
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCdata — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDtd — End current DTD
    • XMLWriter::endDtdAttlist — End current DTD AttList
    • XMLWriter::endDtdElement — End current DTD element
    • XMLWriter::endDtdEntity — End current DTD Entity
    • XMLWriter::endElement — End current element
    • XMLWriter::endPi — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openUri — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startAttributeNs — Create start namespaced attribute
    • XMLWriter::startCdata — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDtd — Create start DTD tag
    • XMLWriter::startDtdAttlist — Create start DTD AttList
    • XMLWriter::startDtdElement — Create start DTD element
    • XMLWriter::startDtdEntity — Create start DTD Entity
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startElementNs — Create start namespaced element tag
    • XMLWriter::startPi — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeAttributeNs — Write full namespaced attribute
    • XMLWriter::writeCdata — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDtd — Write full DTD tag
    • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
    • XMLWriter::writeDtdElement — Write full DTD element tag
    • XMLWriter::writeDtdEntity — Write full DTD Entity tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writeElementNs — Write full namespaced element tag
    • XMLWriter::writePi — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

lingtalfi 08-Oct-2015 08:35
The single quote predefined entity is not escaped.
The other predefined entities are but not the single quote, so you will have to do it yourself.

That's what you would expect:

Ampersand     &     &amp;
Single Quote     '     &apos;
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;

That's what you get with \XmlWriter:

Ampersand     &     &amp;
Single Quote     '     '
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;
Alexey Zakhlestin 09-Jun-2008 03:47
important: XMLWriter expects UTF-8 data from you. It can output xml in various encodings, but input should be strictly utf-8!


Introduction

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object-oriented style or a procedural one. Every method documented describes the alternative procedural call.

User Contributed Notes

There are no user contributed notes for this page.


Installation

The XMLWriter ships with PHP source. This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


Resource Types

Prior to PHP 8.0.0, there was one resource type used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

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

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

The above example will output:

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

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

The above example will output:

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

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

The above example will output:

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

Introduction

Class synopsis

class XMLWriter {
/* Methods */
public endAttribute(): bool
public endCdata(): bool
public endComment(): bool
public endDocument(): bool
public endDtd(): bool
public endDtdAttlist(): bool
public endDtdElement(): bool
public endDtdEntity(): bool
public endElement(): bool
public endPi(): bool
public flush(bool $empty = true): string|int
public fullEndElement(): bool
public openMemory(): bool
public openUri(string $uri): bool
public outputMemory(bool $flush = true): string
public setIndent(bool $enable): bool
public setIndentString(string $indentation): bool
public startAttribute(string $name): bool
public startAttributeNs(?string $prefix, string $name, ?string $namespace): bool
public startCdata(): bool
public startComment(): bool
public startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool
public startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool
public startDtdAttlist(string $name): bool
public startDtdElement(string $qualifiedName): bool
public startDtdEntity(string $name, bool $isParam): bool
public startElement(string $name): bool
public startElementNs(?string $prefix, string $name, ?string $namespace): bool
public startPi(string $target): bool
public text(string $content): bool
public writeAttribute(string $name, string $value): bool
public writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool
public writeCdata(string $content): bool
public writeComment(string $content): bool
public writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool
public writeDtdAttlist(string $name, string $content): bool
public writeDtdElement(string $name, string $content): bool
public writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool
public writeElement(string $name, ?string $content = null): bool
public writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool
public writePi(string $target, string $content): bool
public writeRaw(string $content): bool
}

Table of Contents

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCdata — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDtd — End current DTD
  • XMLWriter::endDtdAttlist — End current DTD AttList
  • XMLWriter::endDtdElement — End current DTD element
  • XMLWriter::endDtdEntity — End current DTD Entity
  • XMLWriter::endElement — End current element
  • XMLWriter::endPi — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openUri — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startAttributeNs — Create start namespaced attribute
  • XMLWriter::startCdata — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDtd — Create start DTD tag
  • XMLWriter::startDtdAttlist — Create start DTD AttList
  • XMLWriter::startDtdElement — Create start DTD element
  • XMLWriter::startDtdEntity — Create start DTD Entity
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startElementNs — Create start namespaced element tag
  • XMLWriter::startPi — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeAttributeNs — Write full namespaced attribute
  • XMLWriter::writeCdata — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDtd — Write full DTD tag
  • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
  • XMLWriter::writeDtdElement — Write full DTD element tag
  • XMLWriter::writeDtdEntity — Write full DTD Entity tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writeElementNs — Write full namespaced element tag
  • XMLWriter::writePi — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

There are no user contributed notes for this page.


End attribute

  • « XMLWriter
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter
  • End attribute

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Description

Object-oriented style

public XMLWriter::endAttribute(): bool

Procedural style

xmlwriter_end_attribute(XMLWriter $writer): bool

Ends the current attribute.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


End current CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • End current CDATA

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — End current CDATA

Description

Object-oriented style

public XMLWriter::endCdata(): bool

Procedural style

xmlwriter_end_cdata(XMLWriter $writer): bool

Ends the current CDATA section.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create end comment

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Create end comment

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Description

Object-oriented style

public XMLWriter::endComment(): bool

Procedural style

xmlwriter_end_comment(XMLWriter $writer): bool

Ends the current comment.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


End current document

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • End current document

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Description

Object-oriented style

public XMLWriter::endDocument(): bool

Procedural style

xmlwriter_end_document(XMLWriter $writer): bool

Ends the current document.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDocument() - Create document tag

User Contributed Notes

Sbastien 13-Mar-2022 09:44
XMLWriter::endDocument() closes properly all remaining elements not yet closed.

Without XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo="
*/
?>

With XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
$xml->endDocument();
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo=""/></b></a>
*/
?>


End current DTD

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • End current DTD

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — End current DTD

Description

Object-oriented style

public XMLWriter::endDtd(): bool

Procedural style

xmlwriter_end_dtd(XMLWriter $writer): bool

Ends the DTD of the document.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD AttList

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • End current DTD AttList

XMLWriter::endDtdAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Description

Object-oriented style

public XMLWriter::endDtdAttlist(): bool

Procedural style

xmlwriter_end_dtd_attlist(XMLWriter $writer): bool

Ends the current DTD attribute list.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD element

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • End current DTD element

XMLWriter::endDtdElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdElement -- xmlwriter_end_dtd_element — End current DTD element

Description

Object-oriented style

public XMLWriter::endDtdElement(): bool

Procedural style

xmlwriter_end_dtd_element(XMLWriter $writer): bool

Ends the current DTD element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD Entity

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • End current DTD Entity

XMLWriter::endDtdEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Description

Object-oriented style

public XMLWriter::endDtdEntity(): bool

Procedural style

xmlwriter_end_dtd_entity(XMLWriter $writer): bool

Ends the current DTD entity.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Description

Object-oriented style

public XMLWriter::endElement(): bool

Procedural style

xmlwriter_end_element(XMLWriter $writer): bool

Ends the current element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


End current PI

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • End current PI

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — End current PI

Description

Object-oriented style

public XMLWriter::endPi(): bool

Procedural style

xmlwriter_end_pi(XMLWriter $writer): bool

Ends the current processing instruction.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Flush current buffer

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Flush current buffer

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Description

Object-oriented style

public XMLWriter::flush(bool $empty = true): string|int

Procedural style

xmlwriter_flush(XMLWriter $writer, bool $empty = true): string|int

Flushes the current buffer.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

empty

Whether to empty the buffer or not. Default is true.

Return Values

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | This function can no longer return false.

User Contributed Notes

Sbastien 13-Mar-2022 09:29
XMLWriter::flush() basic usage with XMLWriter::openMemory() :

<?php
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
$xml->endDocument();
echo $xml->flush();

/*
Produces :

<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


End current element

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Description

Object-oriented style

public XMLWriter::fullEndElement(): bool

Procedural style

xmlwriter_full_end_element(XMLWriter $writer): bool

End the current xml element. Writes an end tag even if the element is empty.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endElement() - End current element

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using memory for string output

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using memory for string output

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Description

Object-oriented style

public XMLWriter::openMemory(): bool

Procedural style

xmlwriter_open_memory(): XMLWriter|false

Creates a new XMLWriter using memory for string output.

Parameters

Return Values

Object-oriented style: Returns true on success or false on failure.

Procedural style: Returns a new XMLWriter for later use with the xmlwriter functions on success, or false on failure.

Changelog

Version | Description
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a resource has been returned in this case.

See Also

  • XMLWriter::openUri() - Create new xmlwriter using source uri for output

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using source uri for output

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using source uri for output

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Description

Object-oriented style

public XMLWriter::openUri(string $uri): bool

Procedural style

xmlwriter_open_uri(string $uri): XMLWriter|false

Creates a new XMLWriter using uri for the output.

Parameters

uri

The URI of the resource for the output.

Return Values

Object-oriented style: Returns true on success or false on failure.

Procedural style: Returns a new XMLWriter instance for later use with the xmlwriter functions on success, or false on failure.

Changelog

Version | Description
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a resource has been returned in this case.

Examples

Example #1 Direct output of XML

It is possible to directly output XML by using the php://output stream wrapper.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

Notes

Note:

On Windows, files opened with this function are locked until the writer is released.

See Also

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

User Contributed Notes

There are no user contributed notes for this page.


Returns current buffer

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Returns current buffer

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Description

Object-oriented style

public XMLWriter::outputMemory(bool $flush = true): string

Procedural style

xmlwriter_output_memory(XMLWriter $writer, bool $flush = true): string

Returns the current buffer.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

flush

Whether to flush the output buffer or not. Default is true.

Return Values

Returns the current buffer as a string.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::flush() - Flush current buffer

User Contributed Notes

There are no user contributed notes for this page.


Toggle indentation on/off

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Toggle indentation on/off

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Description

Object-oriented style

public XMLWriter::setIndent(bool $enable): bool

Procedural style

xmlwriter_set_indent(XMLWriter $writer, bool $enable): bool

Toggles indentation on or off.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

enable

Whether indentation is enabled.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Examples

Example #1 XMLWriter::setIndent() and mixed Content

Enabling indentation is not suitable for mixed content, because the indent string is also inserted before inline elements.

<?php
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('p');
$writer->text('before');
$writer->writeElement('a', 'element');
$writer->text('after');
$writer->endElement();
$writer->endDocument();
echo $writer->outputMemory();
?>

The above example will output:

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

Notes

Note:

The indent is reset when an xmlwriter is opened.

See Also

  • XMLWriter::setIndentString() - Set string used for indenting

User Contributed Notes

info at ensostudio dot ru 04-Apr-2021 01:04
NOTE: $enable can be integer as in example, or boolean.


Set string used for indenting

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Set string used for indenting

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Description

Object-oriented style

public XMLWriter::setIndentString(string $indentation): bool

Procedural style

xmlwriter_set_indent_string(XMLWriter $writer, string $indentation): bool

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

indentation

The indentation string.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Notes

Note:

The indent is reset when an xmlwriter is opened.

See Also

  • XMLWriter::setIndent() - Toggle indentation on/off

User Contributed Notes

There are no user contributed notes for this page.


Create start attribute

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Create start attribute

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Description

Object-oriented style

public XMLWriter::startAttribute(string $name): bool

Procedural style

xmlwriter_start_attribute(XMLWriter $writer, string $name): bool

Starts an attribute.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute name.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Examples

Example #1 Basic XMLWriter::startAttribute() Usage

<?php
$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('element');
$writer->startAttribute('attribute');
$writer->text('value');
$writer->endAttribute();
$writer->endElement();
$writer->endDocument();

The above example will output something similar to:

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

See Also

  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced attribute

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Create start namespaced attribute

XMLWriter::startAttributeNs

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNs -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Description

Object-oriented style

public XMLWriter::startAttributeNs(?string $prefix, string $name, ?string $namespace): bool

Procedural style

xmlwriter_start_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Starts a namespaced attribute.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | prefix is nullable now.

See Also

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start CDATA tag

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • Create start CDATA tag

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Create start CDATA tag

Description

Object-oriented style

public XMLWriter::startCdata(): bool

Procedural style

xmlwriter_start_cdata(XMLWriter $writer): bool

Starts a CDATA.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endCdata() - End current CDATA
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create start comment

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Create start comment

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Description

Object-oriented style

public XMLWriter::startComment(): bool

Procedural style

xmlwriter_start_comment(XMLWriter $writer): bool

Starts a comment.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


Create document tag

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Create document tag

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Description

Object-oriented style

public XMLWriter::startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool

Procedural style

xmlwriter_start_document(
XMLWriter $writer,
?string $version = "1.0",
?string $encoding = null,
?string $standalone = null
): bool

Starts a document.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

version

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

encoding

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

standalone

yes or no.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endDocument() - End current document

User Contributed Notes

Sbastien 13-Mar-2022 09:52
XMLWriter::startDocument() writes the XML declaration.

Without XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<message>Hello World!</message>
*/
?>

With XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


Create start DTD tag

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Create start DTD tag

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Create start DTD tag

Description

Object-oriented style

public XMLWriter::startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool

Procedural style

xmlwriter_start_dtd(
XMLWriter $writer,
string $qualifiedName,
?string $publicId = null,
?string $systemId = null
): bool

Starts a DTD.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endDtd() - End current DTD
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD AttList

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD AttList

XMLWriter::startDtdAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Description

Object-oriented style

public XMLWriter::startDtdAttlist(string $name): bool

Procedural style

xmlwriter_start_dtd_attlist(XMLWriter $writer, string $name): bool

Starts a DTD attribute list.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute list name.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endDtdAttlist() - End current DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD element

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • Create start DTD element

XMLWriter::startDtdElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdElement -- xmlwriter_start_dtd_element — Create start DTD element

Description

Object-oriented style

public XMLWriter::startDtdElement(string $qualifiedName): bool

Procedural style

xmlwriter_start_dtd_element(XMLWriter $writer, string $qualifiedName): bool

Starts a DTD element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endDtdElement() - End current DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD Entity

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD Entity

XMLWriter::startDtdEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Description

Object-oriented style

public XMLWriter::startDtdEntity(string $name, bool $isParam): bool

Procedural style

xmlwriter_start_dtd_entity(XMLWriter $writer, string $name, bool $isParam): bool

Starts a DTD entity.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

isParam

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endDtdEntity() - End current DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


Create start element tag

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Create start element tag

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Description

Object-oriented style

public XMLWriter::startElement(string $name): bool

Procedural style

xmlwriter_start_element(XMLWriter $writer, string $name): bool

Starts an element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced element tag

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Create start namespaced element tag

XMLWriter::startElementNs

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNs -- xmlwriter_start_element_ns — Create start namespaced element tag

Description

Object-oriented style

public XMLWriter::startElementNs(?string $prefix, string $name, ?string $namespace): bool

Procedural style

xmlwriter_start_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Starts a namespaced element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start PI tag

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Create start PI tag

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Create start PI tag

Description

Object-oriented style

public XMLWriter::startPi(string $target): bool

Procedural style

xmlwriter_start_pi(XMLWriter $writer, string $target): bool

Starts a processing instruction tag.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::endPi() - End current PI
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Write text

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Write text

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Description

Object-oriented style

public XMLWriter::text(string $content): bool

Procedural style

xmlwriter_text(XMLWriter $writer, string $content): bool

Writes a text.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the text. The characters <, >, & and " are written as entity references (i.e. &lt;, &gt;, &amp; and &quot;, respectively). All other characters including ' are written literally. To write the special XML characters literally, or to write literal entity references, xmlwriter_write_raw() has to be used.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Write full attribute

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Write full attribute

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Description

Object-oriented style

public XMLWriter::writeAttribute(string $name, string $value): bool

Procedural style

xmlwriter_write_attribute(XMLWriter $writer, string $name, string $value): bool

Writes a full attribute.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Examples

Example #1 Intermixing Sub-elements and Attributes

If writing sub-elements and attributes is intermixed, any attempt to write attributes after the first sub-element will fail and return false.

<?php
$xml = new XMLWriter();
$xml->openMemory();

$xml->startElement('element');
$xml->writeAttribute('attr1', '0');
$xml->writeElement('subelem', '0');
var_dump($xml->writeAttribute('attr2', '0'));
$xml->endElement();

echo $xml->flush();
?>

The above example will output:

bool(false)
<element attr1="0"><subelem>0</subelem></element>

See Also

  • XMLWriter::writeAttributeNs() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced attribute

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Write full namespaced attribute

XMLWriter::writeAttributeNs

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNs -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Description

Object-oriented style

public XMLWriter::writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Procedural style

xmlwriter_write_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Writes a full namespaced attribute.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

value

The attribute value.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full CDATA tag

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Write full CDATA tag

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Write full CDATA tag

Description

Object-oriented style

public XMLWriter::writeCdata(string $content): bool

Procedural style

xmlwriter_write_cdata(XMLWriter $writer, string $content): bool

Writes a full CDATA.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the CDATA.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Examples

Example #1 Basic xmlwriter_write_cdata() Usage

<?php
// set up the document
$xml = new XmlWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData output
$xml->startElement('mycdataelement');
$xml->writeCData("text for inclusion as CData");
$xml->endElement();

// end the document and output
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

The above example will output:

<mydoc>
 <myele>
  <mycdataelement><![CDATA[text for inclusion as CData]​]></mycdataelement>
 </myele>
</mydoc>

See Also

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::endCdata() - End current CDATA

User Contributed Notes

There are no user contributed notes for this page.


Write full comment tag

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • Write full comment tag

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Description

Object-oriented style

public XMLWriter::writeComment(string $content): bool

Procedural style

xmlwriter_write_comment(XMLWriter $writer, string $content): bool

Writes a full comment.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the comment.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD tag

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Write full DTD tag

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Write full DTD tag

Description

Object-oriented style

public XMLWriter::writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Procedural style

xmlwriter_write_dtd(
XMLWriter $writer,
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Writes a full DTD.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

content

The content of the DTD.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::endDtd() - End current DTD

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD AttList tag

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD AttList tag

XMLWriter::writeDtdAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Description

Object-oriented style

public XMLWriter::writeDtdAttlist(string $name, string $content): bool

Procedural style

xmlwriter_write_dtd_attlist(XMLWriter $writer, string $name, string $content): bool

Writes a DTD attribute list.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::endDtdAttlist() - End current DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD element tag

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Write full DTD element tag

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Description

Object-oriented style

public XMLWriter::writeDtdElement(string $name, string $content): bool

Procedural style

xmlwriter_write_dtd_element(XMLWriter $writer, string $name, string $content): bool

Writes a full DTD element.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::endDtdElement() - End current DTD element

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD Entity tag

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD Entity tag

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Description

Object-oriented style

public XMLWriter::writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Procedural style

xmlwriter_write_dtd_entity(
XMLWriter $writer,
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Writes a full DTD entity.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | publicId, systemId and notationData are nullable now.

See Also

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::endDtdEntity() - End current DTD Entity

User Contributed Notes

There are no user contributed notes for this page.


Write full element tag

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Write full element tag

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Description

Object-oriented style

public XMLWriter::writeElement(string $name, ?string $content = null): bool

Procedural style

xmlwriter_write_element(XMLWriter $writer, string $name, ?string $content = null): bool

Writes a full element tag.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

content

The element contents.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced element tag

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Write full namespaced element tag

XMLWriter::writeElementNs

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNs -- xmlwriter_write_element_ns — Write full namespaced element tag

Description

Object-oriented style

public XMLWriter::writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Procedural style

xmlwriter_write_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Writes a full namespaced element tag.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

content

The element contents.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startElementNs() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Writes a PI

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Writes a PI

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Writes a PI

Description

Object-oriented style

public XMLWriter::writePi(string $target, string $content): bool

Procedural style

xmlwriter_write_pi(XMLWriter $writer, string $target, string $content): bool

Writes a processing instruction.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::endPi() - End current PI

User Contributed Notes

There are no user contributed notes for this page.


Write a raw XML text

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Write a raw XML text

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Description

Object-oriented style

public XMLWriter::writeRaw(string $content): bool

Procedural style

xmlwriter_write_raw(XMLWriter $writer, string $content): bool

Writes a raw xml text.

Parameters

writer

Only for procedural calls. The XMLWriter instance that is being modified. This object is returned from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The text string to write.

Return Values

Returns true on success or false on failure.

Changelog

Version | Description
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

See Also

  • XMLWriter::text() - Write text

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Example collection.xml and collection.xsl files
    • Error handling with libxml error handling functions
  • XSLTProcessor — The XSLTProcessor class
    • XSLTProcessor::__construct — Creates a new XSLTProcessor object
    • XSLTProcessor::getParameter — Get value of a parameter
    • XSLTProcessor::getSecurityPrefs — Get security preferences
    • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet — Import stylesheet
    • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter — Remove parameter
    • XSLTProcessor::setParameter — Set value for a parameter
    • XSLTProcessor::setProfiling — Sets profiling output file
    • XSLTProcessor::setSecurityPrefs — Set security preferences
    • XSLTProcessor::transformToDoc — Transform to a document
    • XSLTProcessor::transformToUri — Transform to URI
    • XSLTProcessor::transformToXml — Transform to XML

User Contributed Notes

Jaroslaw Zabiello 23-Jun-2011 07:10
This is more usefull, no files needed, it just takes XML and XSL strings as input parameters and returns transformed XML

<?php
/**
 * @param  $xml
 * @param  $xsl
 * @return string xml
 */
function transform($xml, $xsl) {
   $xslt = new XSLTProcessor();
   $xslt->importStylesheet(new  SimpleXMLElement($xsl));
   return $xslt->transformToXml(new SimpleXMLElement($xml));
}
?>
sudhir dot vis at gmail dot com 25-Apr-2009 11:40
Here is a simplest way to transform the xml from php

<?php
$sXml  = "<xml>";
$sXml .= "<sudhir>hello sudhir</sudhir>";
$sXml .= "</xml>";

# LOAD XML FILE
$XML = new DOMDocument();
$XML->loadXML( $sXml );

# START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load( 'xsl/index.xsl', LIBXML_NOCDATA);
$xslt->importStylesheet( $XSL );
#PRINT
print $xslt->transformToXML( $XML );
?>
allens at nospam dot com 19-Apr-2009 08:45
Problem:
Getting Netbeans error message:
Fatal error: Class 'xsltprocessor' not found

Solution:
place copy of php.ini in the c:\windows directory!

by default the php.ini file has xsl disabled......search for the line

;extension=php_xsl.dll

to enable XSL....remove ; so that the extension gets included

Then if Netbeans gives you the following message:
PHP Startup: Unable to load dynamic library './php_xsl.dll'

then you need to run the php-5.2.9-1-win32-installer.msi again
this time selecting the XSL extension!
visual77 at gmail dot com 20-Sep-2008 04:35
The XSLTProcessor is kind of a pain to use to generate an entire website, mostly due to the tedious process of building an XML tree through DOMDocument's createElement and appendChild functions.

To get an entire website out of nothing but XML and XSL (which really is a superior system to just echoing out the HTML), you could use an object that does all the PHP data structure to XML data tree conversion, and combines with the XSLTProcessor for rendering. A good object like this is DOMi, which you can find at http://domi.sourceforge.net.
emilise dot victor at gmail dot com 12-Mar-2008 08:10
Here is a way to get an output without using <xml:message> : use the var_dump function of php :
- First bind the php functions with
<? $xslt->registerPHPFunctions() ?>
and xmlns:php="http://php.net/xsl" in the stylesheet
- Then you can call the var_dump function like this : <xsl:variable name="a" select="php:function('var_dump', $return)" />

I couldn't find a way to call the function and have it really print the result without creating a variable, but well, it's just for debugging...
shangxiao at php dot net 10-Jan-2008 05:38
When using the DOM api to add xsl commands to your stylesheet dynamically, be sure to use createElementNS() rather than createElement() otherwise the XSLTProcessor will not recognise these DOM nodes.

Eg:
$xsl->createElementNS('http://www.w3.org/1999/XSL/Transform', 'xsl:element');
pb at online-magazin dot at 11-Oct-2007 03:13
Calling the Saxon XSLT Processor is a very esay task to do!

You just need to do some simple task

1. Install the JavaBridge for PHP

2. Download the freeware (B) Saxon distribution from http://saxon.sourceforge.net/

3. Put the jar files in a directory whre you have access

4. Use this sample of code

// Directory where the jar files are located
define("SAXON_DIR", $_SERVER['DOCUMENT_ROOT']."/saxonb8.9.0/");

// include the jars
java_require(SAXON_DIR."saxon8.jar;".SAXON_DIR."saxon8-dom.jar");

$sXslFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xsl"; // The xsl file
$sXmlFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xml"; // The xml file

try
{
  $oXslSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXslFile);
  $oXmlSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXmlFile);

  $oFeatureKeys = new JavaClass("net.sf.saxon.FeatureKeys");

  // Create the Factory
  $oTransformerFactory = new java("net.sf.saxon.TransformerFactoryImpl");

  //Disable source document validation
  $oTransformerFactory->setAttribute($oFeatureKeys->SCHEMA_VALIDATION, 4);

  // Create a new Transformer
  $oTransFormer = $oTransformerFactory->newTransformer($oXslSource);

  // Create a StreamResult to store the output
  $oResultStringWriter = new java("java.io.StringWriter");
  $oResultStream = new java("javax.xml.transform.stream.StreamResult", $oResultStringWriter);

  // Transform
  $oTransFormer->transform($oXmlSource, $oResultStream);

  // Echo the output from the transformation
  echo java_cast($oResultStringWriter->toString(), "string");

}
catch(JavaException $e){
   echo java_cast($e->getCause()->toString(), "string");
   exit;
}

5. Enjoy

This is working quite well.
Vasil Rangelov 21-Aug-2007 07:31
@basslines at gmail dot com
"
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
"

Using SAXON or AltovaXML by using their JAVA bindings could prove to be a difficult task to do, and .NET seems to be buggy (at least for me). However, I've made a class that uses SAXON or AltovaXML from the command line. AltovaXML could also be used with COM, provided it's registered as a COM component.

You can download my wrapper from:
http://xslt2processor.sourceforge.net/

I still need to implement a more graceful error handling (the way the XSL extension uses the Libxml functions), and once the bug
http://bugs.php.net/bug.php?id=41577
is fixed, I'll implement the .NET interfaces too.

I'll appreciate any feedback.
geoffreyj dot lee at gmail dot com 01-Jul-2007 11:02
Here are a couple useful tips for those who care about cross-browser compatibility.

Given:

<script type="text/javascript" src="test.js"></script>

XSLT will automatically condense it to:

<script type="text/javascript" src="test.js"/>

While this is good, Internet Explorer breaks on empty script tags. So, the simple solution is to add something to prevent an empty tag. For example:

<script type="text/javascript" src="test.js"><xsl:comment/></script>

Produces:

<script type="text/javascript" src="test.js">

</script>

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

Also, here is a way to use IE's conditional comments:

<xsl:comment>[if gte IE 5]&#62;
&#60;link rel="stylesheet" type="text/css" href="ie.css" /&#62;
&#60;![endif]</xsl:comment>

Produces:

<!--[if gte IE 5]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

This will let you isolate IE-related CSS without needing to use ugly CSS hacks.
gabriel dot birke at web dot de 10-May-2007 03:19
Each <xsl:message> tag will generate a PHP error (level Warning). If you want to collect and pretty-print them, you could use a custom error handling function that collects the warnings in a static variable.
mnot at mnot dot net 08-May-2007 08:59
You can set an HTTP proxy for the XSLT document() function to use (as well as DTD external references) by setting http_proxy in the environment.

E.g., in Apache configuration;

SetEnv http_proxy http://127.0.0.1:3128/
Ryan D. Hatch 02-May-2007 01:14
Looking for php_xsl.dll?

If you installed on Windows using the MSI Installer - you may not have it.

1.) Add/Remove Programs and Change PHP Installation.  Select XSL Extension.

OR

2.) Download complete .zip file of PHP and you can copy php_xsl.dll into your PHP/etc directory.

Just a note.

Ryan D. Hatch
adrian at foeder dot de 14-Sep-2006 02:45
If you want to use the document()-function inside your XSL stylesheet, please note that you have to use an absolute path there.
Important for windows users: the absolute path *has* to be with forward slashes, so subsitute windows-path-backslashes to forward slashes before you transform the document.

Examples:
This will NOT work:
<xsl:copy-of select="document('test.xml')" />

This will also NOT work:
<xsl:copy-of select="document('c:\temp\test.xml')" />

But this WILL work:
<xsl:copy-of select="document('c:/temp/test.xml')" />
27-Apr-2006 06:26
Enable libxslt library, PHP 5, under windows:

To Enable:
In your php.ini
1. Uncomment ;extension=php_xsl.dll
2. Change extension_dir to
     extension_dir = "./ext"

To Confirm:
1. In a test.php page:
<?php phpinfo() ?>
2. Run test.php
3. Search for "libxslt Version". It should return a version number in a XSL headed table.

Further info Google
"Configuring and Testing PHP Servers for XSL Support"
Fabrice Bonny 30-Mar-2006 01:34
In response to how to use entities from DTD (internal or external) in XSLT. It works if you do this way:

$xsl = new DOMDocument;
$xsl->resolveExternals = TRUE;
$xsl->substituteEntities = TRUE;
$xsl->load(...);

Hope this helps! ;-)
basslines at gmail dot com 29-Mar-2006 10:07
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
17-Mar-2006 09:14
In response to appletalk at gmail dot com
<snip>
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:
Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...
There're many ways to solve this:
.....
b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
   <!ENTITY nbsp "&#160;" >
   ]>
.......</snip>
Just wanted to let people know that option b does NOT work. I'm not sure why this isn't implemented correctly, but it isn't, so don't waste your time. It's unfortunate the DOMXSL transform is so much less capable than the old xslt function.
venkatesh at lammersmedical dot com 01-Mar-2005 06:17
Here is function to read from the XSL sheet which is saved as a text file.

function ReadExcelSheet($filename){
             $test=file($filename);
             $ar1=str_replace("~[^\t]*\t","\t",$test);
             $ar2=str_replace("~","",$ar1);
             $ar=str_replace("?","",$ar2);
             $temp=array();
             for ($i=0; $i<count($ar); $i++) {
                       if((substr($ar[$i],0,1)!= "\t")){
                           if($ar[$i]!=="\r\n"){
                           array_push($temp,$ar[$i]);
            }
        }
    }
    $name=split("\t",$temp[0]);
    $ExcelList=array();
    for($i=1;$i<count($temp);$i++){
        $split_result=split("\t",$temp[$i]);
        array_push($ExcelList,$split_result);
    }
    $result=insert_into_array($ExcelList,0,$name);
    return($result);
}
appletalk at gmail dot com 04-Feb-2005 10:32
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:

Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...

There're many ways to solve this:
a) The hard way
<xsl:text disable-output-escaping="yes"> &amp;nbsp;</xsl:text>

b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
   <!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp "&#160;" >
    ]>

c) External Doctype
Just in case you want need other HTML entities, you can call an external doctype with the proper definitions

<!DOCTYPE page SYSTEM "http://gv.ca/dtd/character-entities.dtd">

Of course, you can download the file and place it in your server.
kekoajs at yahoo dot com 22-Dec-2004 02:07
Wow, I spent the better part of a day looking for how one could pass an entire test expression to an XSL stylesheet.  It seems that the XSLT 1.0 specification doesn't support it but PHP 5 (and maybe 4s) inclusion of  EXSLT allows one to do exactly that...

simply add these lines...

xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn"

to the <xsl:stylesheet> element and when using an expression stored in a <xsl:param> element write

<xsl:if test="dyn:evaluate($param-name)">

and viola!  you can now use expressions generated externally in your stylesheet!

EXSLT adds many useful functions that can be integrated into your XSL in a similar fashion.  You can go to http://exslt.org/ to learn more...
rd at jerntorget dot se 24-Sep-2004 03:58
If you get the following warning message:

xsltApplyOneTemplate: _if_ was not compiled in (if can for example be apply-template or some other method), i've found that the problem seems to be an &nbsp; directly before the <xsl:if> or what ever is causing the problem.

One way to get thru the problem is to use span tags around &nbsp;  like : <span>&nbsp;</span>
jw at jwscripts dot com 06-Sep-2004 02:23
The following code is a wrapper to support calls to some of the old xslt_* functions:

<?

if (PHP_VERSION >= 5) {
    // Emulate the old xslt library functions
    function xslt_create() {
        return new XsltProcessor();
    }

    function xslt_process($xsltproc,
                          $xml_arg,
                          $xsl_arg,
                          $xslcontainer = null,
                          $args = null,
                          $params = null) {
        // Start with preparing the arguments
        $xml_arg = str_replace('arg:', '', $xml_arg);
        $xsl_arg = str_replace('arg:', '', $xsl_arg);

        // Create instances of the DomDocument class
        $xml = new DomDocument;
        $xsl = new DomDocument;

        // Load the xml document and the xsl template
        $xml->loadXML($args[$xml_arg]);
        $xsl->loadXML($args[$xsl_arg]);

        // Load the xsl template
        $xsltproc->importStyleSheet($xsl);

        // Set parameters when defined
        if ($params) {
            foreach ($params as $param => $value) {
                $xsltproc->setParameter("", $param, $value);
            }
        }

        // Start the transformation
        $processed = $xsltproc->transformToXML($xml);

        // Put the result in a file when specified
        if ($xslcontainer) {
            return @file_put_contents($xslcontainer, $processed);
        } else {
            return $processed;
        }

    }

    function xslt_free($xsltproc) {
        unset($xsltproc);
    }
}

$arguments = array(
    '/_xml' => file_get_contents("newxslt.xml"),
    '/_xsl' => file_get_contents("newxslt.xslt")
);

$xsltproc = xslt_create();
$html = xslt_process(
    $xsltproc,
    'arg:/_xml',
    'arg:/_xsl',
    null,
    $arguments
);

xslt_free($xsltproc);
print $html;

?>
rojaro 23-Jun-2004 07:43
If you're want to use XML from a variable e.g. $xmldata but the XSLT-StyleSheet from a file, you can do it also the following way:

<?php
$xslt = new xsltProcessor;
$xslt->importStyleSheet(DomDocument::load('filename.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($xmldata));
?>


Introduction

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library

User Contributed Notes

There are no user contributed notes for this page.


Requirements

This extension requires the libxml PHP extension. This means passing the --with-libxml, or prior to PHP 7.4 the --enable-libxml, configuration flag, although this is implicitly accomplished because libxml is enabled by default.

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

User Contributed Notes

There are no user contributed notes for this page.


Installation

PHP includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line (DIR being the libxslt installation directory).

User Contributed Notes

There are no user contributed notes for this page.


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XSL_CLONE_AUTO (int)
XSL_CLONE_NEVER (int)
XSL_CLONE_ALWAYS (int)
LIBXSLT_VERSION (int)
libxslt version like 10117.
LIBXSLT_DOTTED_VERSION (string)
libxslt version like 1.1.17.
LIBEXSLT_VERSION (int)
libexslt version like 813.
LIBEXSLT_DOTTED_VERSION (string)
libexslt version like 1.1.17.
XSL_SECPREF_NONE (int)
Deactivate all security restrictions.
XSL_SECPREF_READ_FILE (int)
Disallows reading files.
XSL_SECPREF_WRITE_FILE (int)
Disallows writing files.
XSL_SECPREF_CREATE_DIRECTORY (int)
Disallows creating directories.
XSL_SECPREF_READ_NETWORK (int)
Disallows reading network files.
XSL_SECPREF_WRITE_NETWORK (int)
Disallows writing network files.
XSL_SECPREF_DEFAULT (int)
Disallows all write access, i.e. a bitmask of XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.

User Contributed Notes

There are no user contributed notes for this page.


Examples

Table of Contents

  • Example collection.xml and collection.xsl files
  • Error handling with libxml error handling functions

User Contributed Notes

There are no user contributed notes for this page.


Example collection.xml and collection.xsl files

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

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

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


Error handling with libxml error handling functions

libxml offers a number of functions for handling errors, which can be employed to capture and deal with errors in XSLT processing.

Example #1 fruits.xml

A valid XML file.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Example #2 fruits.xsl

Contains an invalid select expression.

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

Example #3 Collating and printing errors

The example below captures and displays libxml errors raised when calling XSLTProcessor::importStyleSheet() with a stylesheet containing an error.

<?php

$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xsl = new XSLTProcessor();

$xmldoc->loadXML('fruits.xml');
$xsldoc->loadXML('fruits.xsl');

libxml_use_internal_errors(true);
$result = $xsl->importStyleSheet($xsldoc);
if (!$result) {
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}
libxml_use_internal_errors(false);

if ($result) {
echo $xsl->transformToXML($xmldoc);
}

?>

The above example will output something similar to:

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.


The XSLTProcessor class

(PHP 5, PHP 7, PHP 8)

Introduction

Class synopsis

class XSLTProcessor {
/* Methods */
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
}

Table of Contents

  • XSLTProcessor::__construct — Creates a new XSLTProcessor object
  • XSLTProcessor::getParameter — Get value of a parameter
  • XSLTProcessor::getSecurityPrefs — Get security preferences
  • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
  • XSLTProcessor::importStylesheet — Import stylesheet
  • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
  • XSLTProcessor::removeParameter — Remove parameter
  • XSLTProcessor::setParameter — Set value for a parameter
  • XSLTProcessor::setProfiling — Sets profiling output file
  • XSLTProcessor::setSecurityPrefs — Set security preferences
  • XSLTProcessor::transformToDoc — Transform to a document
  • XSLTProcessor::transformToUri — Transform to URI
  • XSLTProcessor::transformToXml — Transform to XML

User Contributed Notes

joandres52725lm at gmail dot com 29-Apr-2020 07:29
[Update] PHP version /.3.15 and Windows Uncomment `extension=xsl` to activate it in your php.ini. Then restart your webserver to refresh php.
tschallacka 29-Feb-2016 09:58
uncomment extension=php_xsl.dll on windows to activate it in your php.ini. Then restart your webserver to refresh php.
flavius 13-Nov-2015 05:49
It requires PHP5 XSL extension. On linux:

sudo apt-get install php5-xsl


Creates a new XSLTProcessor object

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Creates a new XSLTProcessor object

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Creates a new XSLTProcessor object

Description

XSLTProcessor::__construct()

Creates a new XSLTProcessor object.

Parameters

This function has no parameters.

Examples

Example #1 Creating an 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.


Get value of a parameter

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Get value of a parameter

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Get value of a parameter

Description

public XSLTProcessor::getParameter(string $namespace, string $name): string|false

Gets a parameter if previously set by XSLTProcessor::setParameter().

Parameters

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

Return Values

The value of the parameter (as a string), or false if it's not set.

See Also

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

User Contributed Notes

There are no user contributed notes for this page.


Get security preferences

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Get security preferences

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Get security preferences

Description

public XSLTProcessor::getSecurityPrefs(): int

Gets the security preferences.

Parameters

This function has no parameters.

Return Values

A bitmask consisting of XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.

User Contributed Notes

There are no user contributed notes for this page.


Determine if PHP has EXSLT support

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Determine if PHP has EXSLT support

XSLTProcessor::hasExsltSupport

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

XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support

Description

public XSLTProcessor::hasExsltSupport(): bool

This method determines if PHP was built with the » EXSLT library.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>

User Contributed Notes

There are no user contributed notes for this page.


Import stylesheet

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Import stylesheet

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Import stylesheet

Description

public XSLTProcessor::importStylesheet(object $stylesheet): bool

This method imports the stylesheet into the XSLTProcessor for transformations.

Parameters

stylesheet

The imported style sheet as a DOMDocument or SimpleXMLElement object.

Return Values

Returns true on success or false on failure.

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!


Enables the ability to use PHP functions as XSLT functions

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Enables the ability to use PHP functions as XSLT functions

XSLTProcessor::registerPHPFunctions

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

XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions

Description

public XSLTProcessor::registerPHPFunctions(array|string|null $functions = null): void

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Parameters

functions

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

Return Values

No value is returned.

Examples

Example #1 Simple PHP Function call from a 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>Users</h2>
<table>
<xsl:for-each select="user">
<tr><td>
<xsl:value-of
select="php:function('ucfirst',string(uid))"/>
</td></tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = new DOMDocument();
$xmldoc->loadXML($xml);
$xsldoc = new DOMDocument();
$xsldoc->loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

User Contributed Notes

Matthew, info at mathias-schaefer dot de 25-Nov-2010 08:34
=> there is no instance of your class needed, you have to take care about the namespace (using 5.3).

<!-- xsl:
<xsl:value-of select="php:function ('My\Name\Space\MyClassName::methodName',1+2)"/>
--->

<?php
namespace My\Name\Space;

   class MyClassName
   {
      static public function methodName($someArgument)
      {
         return "resultis:".$someArgument;
      }
   }
?>

<!-- result:
resultis:3
-->

=> no to-string conversion of the argument needed
=> returning numbers is also possible (maybe DOM nodes too)

Keep on hackin'
Demerit 10-Aug-2010 07:58
Let's get the terminology correct here, folks.

If you are calling a function that is residing within a class, reference it by its INSTANCE name, NOT its class name.

class.my_class.php:

<?php
class class_name {
static function function_name($in){
return ($out);
}
}
?>

calling_document.php:

<?php
require_once('class.my_class.php');
$instance_name=new class_name();
?>

my_xslt.xsl:

<xsl:value-of select="php:function ('instance_name::function_name','garbage')" />

BTW, in 5.1.6 double-colon (::) is the only thing that works when calling a function that resides within a class. However, you must declare your function as static. Using -> as some have suggested (e.g., php:function ('instance_name->function_name','garbage')) doesn't work at all, no matter how you declare your function.
Nic Luciano 22-Jul-2009 11:09
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."

Also note that the class function must be declared as static.
Ariz Jacinto 08-Jul-2008 02:21
If you want to use replace() function similar to XPath 2.0[1]  and you want to avoid a long XSLT function similar to this one[2], you can use PHP's str_replace() instead:

   <xsl:value-of select="php:functionString('str_replace','pattern', 'replacement' , . )">

Links:
  [1] http://www.w3.org/TR/2004/WD-xpath-functions-20041029/#func-replace
  [2] http://aspn.activestate.com/ASPN/Cookbook/XSLT/Recipe/65426

_
thsoft at vipmail dot hu 27-Dec-2007 02:22
Unfortunately, you can't pass arrays to PHP from XLST.
But you can pass an arbitrary number of arguments to a PHP function and then get them with func_get_args() as an array.
[There's no sense writing a function that is identical to the array() construct, because a function's return value is converted to a string when passed as an argument to another function. This means deep arrays cannot be handled this way.]
thsoft at vipmail dot hu 31-Jan-2007 03:20
The correct way to receive DOM nodes (let it be element, document, document fragment etc.) returned from PHP is to use <xsl:copy-of select="php:function...

I found the idea and an example here: http://bugs.php.net/bug.php?id=29409

For the technical details about the reason, see http://www.w3.org/TR/xslt#copy-of
phil at worldpoolfederation dot com 01-Dec-2006 03:22
Not true

Use :: to call static functions
Use -> to call non static functions

You must define a function as static in php 5.1 to be able to call it statically.
mark at thirst dot org 10-Oct-2006 07:25
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."   This worked in 5.0.4 but no longer works in 5.1.6.
franp at free dot fr 02-Sep-2006 01:45
Note that if you want your output to validate against some xhtml dtd, you must add the following attribute to the xsl:stylesheet element of the xslt stylesheet :
exclude-result-prefixes="php".

Otherwise, you get an "invalid attribute xmlns:php" error.
taylorbarstow at that google mail thingy 26-May-2006 05:33
Add-on to my previous note (below) about returning nodesets to XSLT from PHP functions:

You don't have to return a DOMDocument, DOMElement works just as well.  Plus, retuning a DOMElement gets around the problem of discarding the root node which I discuss below and which is also touched on by "Ingram".
heinemann dot juergen at hjcms dot de 08-Mar-2006 02:23
You can find mor Examples at PHP Sources php-5.*/ext/xsl/tests
<?php

$xform = <<<EOT
<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:php="http://php.net/xsl"
    xsl:extension-element-prefixes="php"
>
<xsl:output method="xml" indent="yes" encoding="utf-8" />
<xsl:namespace-alias stylesheet-prefix="php" result-prefix="xsl" />
<xsl:template match="root">
<html>
<head>
    <title>Dateformat</title>
</head>
<body>
<xsl:for-each select="datenode">
    <li>
        <xsl:value-of select="php:functionString('convertDate', . )" />
    </li>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
EOT;

function convertDate( $i )
{
    setlocale( LC_TIME, 'de_DE' );
    return utf8_encode( strftime( '%B %d %A %Y %H:%M:%S CET', $i ) );
}

$xsl = new XSLTProcessor;
$xsl->registerPHPFunctions();
$xsl->setParameter( 'DOCTYPE', 'PUBLIC', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' );
$xsl->setParameter( 'html', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$xdom = new DomDocument( '1.0', 'utf-8' );
$xdom->loadXML( $xform );

$xsl->importStyleSheet( $xdom );
unset( $xdom );

$dom = new DomDocument( '1.0', 'utf-8' );
$r = $dom->appendChild( $dom->createElement( 'root' ) );
foreach ( range( 1, 12 ) AS $i ) {
    $r->appendChild( $dom->createElement( 'datenode', mktime( date('G'), date('i'), date('s'), $i, date('d'), date('Y') ) ) );
}

header( "Content-Type: text/html; charset=utf-8;" );
header( "Content-Encoding: utf-8" );
echo $xsl->transformToXML( $dom );

?>
Ingram 28-Feb-2006 12:33
Upon testing returning of a nodeset contributed by

taylorbarstow at that google mail thingy

(which works excellently, TY!)

I found that with using:

===
"Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" /> "
===

I could only output the text and not any of the tags after applying templates - i.e. it stripped all elements around text.

Instead using:

===
<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
     <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.
===

Worked fine and allowed me to apply-templates without problem on the returned nodeset.
hopeseekr at gmail dot com 01-Feb-2006 12:17
One of the peskiest things I had problems with was encoding URL parameters.  I mean, pretend you want to populate a link with "search+terms" instead of just "search terms".  I was including two seperate URLs in the XML and that was ludicrous.

Below is a far more elegant PHP+XSLT solution.  You will also see it uses two *undocumented* features of registerPHPFunctions(), namely php:functionString() and the passing of parameters to the function.  I figured this out by trial and error; I really hope this note helps you as it *greatly* expands the power of php functions in XSLT!

<?php
/* --- XML input --- */
<search_results>
   <query>concert tickets</query>
</search_results>

/* --- XSL code --- */
<!-- Display query -->
<xsl:template match="search_results">
   <!-- Get URL-encoded string via PHP -->
   <xsl:variable name="safeurl" as="xs:string" select="php:functionString('urlencode', query)" />
   <p>Your search for <em><xsl:value-of select="query"/></em> can be continued at <a href="http://www.tixtix.com/search.php?q={$safeurl}">our search engine</a></p>
</xsl:template>

/* --- XHTML output --- */
<p>Your search for <em>concert tickets</em> can be continued at <a href="http://www.tixtix.com/search.php?q=space+cowboy">our search engine</a></p>
?>

Cool, huh?
taylorbarstow at that google mail thingy 01-Dec-2005 07:14
From a PHP function, you can pass a nodeset back to XSL using a DOMDocument.  For example:

<?php

function getNodeSet() {
   $xml =
       "<test>" .
       "<a-node>This is a node</a-node>" .
       "<a-node>This is another node</a-node>" .
       "</test>";
   $doc = new DOMDocument;
   $doc->loadXml($xml);
   return $doc;
}

?>

The only problem I've found is that the root level node in your returned DOM document acts like the root level node of your original.   SO, it's easy to introduce an infinite loop like so:

<xsl:template match="/">
   <xsl:apply-templates select="php:function('getNodeSet')" />
</xsl:template>

To avoid this, I've been using a construct like:

<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
      <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.  Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" />
Ritch at Bugsoftware dot co dot uk 22-Jun-2005 03:18
If you wish to use a function from inside a class use the double colon (::) notation, for example;

php:functionString('classname::function')

The funtion is fired off as a static and as such acts like a function in the global namespace.
benbarnett 04-Mar-2005 04:34
You can use the php:functionString() in the XSL, which will automatically convert output to a string!
zac at zacbowling dot com 27-Oct-2004 01:48
One thing I have told a lot of people to do if they are having
issues with this function is to check for any 'xmlns' attributes
that get generated and added to your xml pages by some
types of popular software.

<?php
$file = "http://data.map***.net/m***ck.asmx/GetMessages?IMEI=$id";

$docxml = file_get_contents($file);

//You may have to do something like this where
//I remove any instance of xmlns tags that get
//returned by my ASP.NET SOAP responses.

$docxml =
 str_replace("xmlns=\"http://data.map***.net/m***ck.asmx?WSDL\"",
  "",$docxml);

$xslt = new xsltProcessor;

//You don't remove them then this function will blow up.
$xslt->registerPHPFunctions();
$xslt->importStyleSheet(DomDocument::load('../xsl/message.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($docxml));

?>

Also a few cool tricks with this function is that you can call
built in PHP functions. For example:

<xsl:value-of
  select="php:function('nl2br',string(MessageContent/Message))"
  disable-output-escaping="yes"/>

That XSL value will now return your normal string but replace
all your new line charactors in your xml with '<br />'s.

Also note the 'disable-output-escaping="yes"' statement. If
you don't call this, then the output of that bind will be ran
thru basicly a "htmlencode()" type function.

Last but not least, take a look at the 'string()' function I
called in XSL before passing it back. That is because without
calling that, when it runs it will try and pass the node object,
and not its value (which is what you most likely only want).

This function is very awsome and could lead to some very
interesting code development. Skins could be loaded
remotely. You could write an RSS viewer in PHP without much
code. You could parse XHTML pages into another view (either
localy or remotely). Then you can take that same XML
content and throw it against ASP.NET, Java, or even a
command line processing tool using that same exact XSL
style sheet and generate the front ends for you page without
much change. I'm very excited.

Happy codding.
junkmail at eighteyes dot com 08-Oct-2004 02:52
When writing a stylesheet that uses a callback function be sure to include a namespace declaration for php, as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl" version='1.0'>
begemot at php dot com dot ua 28-Sep-2004 06:24
I think it help  your.
<?php

function dateLang () {
        return strftime("%A");
}

$xsl = new DomDocument();
$xsl->load("datetime.xsl");
$inputdom = new DomDocument();
$inputdom->load("today.xml");

$proc = new XsltProcessor();
$proc->registerPhpFunctions();

// Load the documents and process using $xslt
$xsl = $proc->importStylesheet($xsl);

/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);

print $newdom->saveXML();

?>

Here's the XSLT stylesheet, datetime.xsl, that will call that function:

<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:template match="/">
  <xsl:value-of select="php:function('dateLang')" />
</xsl:template>
</xsl:stylesheet>

And here's an absolute minimal XML file, today.xml, to pass through the stylesheet (although articles.xml would achieve the same result):

<?xml version="1.0" encoding="iso-8859-1" ?>
<today></today>
zac at zacbowling dot com 26-Aug-2004 09:48
One thing to note about this function. A lot of values need to be converted to a XSLT string using the "string()" function in XLS before you pass them to your functions, and when you return them make sure that if they are strings that you call the "strval()" in php before doing so. This saved me hours.

Hope that helps.

Zac Bowling


Remove parameter

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Remove parameter

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Remove parameter

Description

public XSLTProcessor::removeParameter(string $namespace, string $name): bool

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

Parameters

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

Return Values

Returns true on success or false on failure.

See Also

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::getParameter() - Get value of a parameter

User Contributed Notes

There are no user contributed notes for this page.


Set value for a parameter

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Set value for a parameter

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Set value for a parameter

Description

public XSLTProcessor::setParameter(string $namespace, string $name, string $value): bool
public XSLTProcessor::setParameter(string $namespace, array $options): bool

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

Parameters

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Changing the owner before the transformation

<?php

$collections = array(
'Marc Rutkowski' => 'marc',
'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

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

?>

See Also

  • XSLTProcessor::getParameter() - Get value of a parameter
  • XSLTProcessor::removeParameter() - Remove 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.


Sets profiling output file

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Sets profiling output file

XSLTProcessor::setProfiling

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

XSLTProcessor::setProfiling — Sets profiling output file

Description

public XSLTProcessor::setProfiling(?string $filename): true

Sets the file to output profiling information when processing a stylesheet.

Parameters

filename

Path to the file to dump profiling information.

Return Values

Always returns true.

Examples

Example #1 Example profiling output

<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

The above code will produce the following information in the profiling file:

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.


Set security preferences

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Set security preferences

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Set security preferences

Description

public XSLTProcessor::setSecurityPrefs(int $preferences): int

Sets the security preferences.

Parameters

preferences

The new security preferences. The following constants can be ORed: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternatively, XSL_SECPREF_NONE or XSL_SECPREF_DEFAULT can be passed.

Return Values

Returns the old security preferences.

User Contributed Notes

There are no user contributed notes for this page.


Transform to a document

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri »
  • PHP Manual
  • XSLTProcessor
  • Transform to a document

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transform to a document

Description

public XSLTProcessor::transformToDoc(object $document, ?string $returnClass = null): object|false

Transforms the source node to a document (e.g. DOMDocument) applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parameters

document

The DOMDocument or SimpleXMLElement or libxml-compatible object to be transformed.

returnClass

This optional parameter may be used so that XSLTProcessor::transformToDoc() will return an object of the specified class. That class should either extend or be the same class as document's class.

Return Values

The resulting document or false on error.

Examples

Example #1 Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

The above example will output:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

See Also

  • XSLTProcessor::transformToUri() - Transform to URI
  • XSLTProcessor::transformToXml() - Transform to XML

User Contributed Notes

franp at free dot fr 30-Aug-2006 05:16
In most cases if you expect XML (or XHTML) as output you better use transformToXML() directly. You gain better control over xsl:output attributes, notably omit-xml-declaration.

Instead of :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$dom = $proc->transformToDoc($xml);
echo $dom->saveXML();

do use :
$proc = new XSLTProcessor();
$proc->importStylesheet($xsl);
$newXml = $proc->transformToXML($xml);
echo $newXml;

In the first case, <?xml version="1.0" encoding="utf-8"?> is added whatever you set the omit-xml-declaration while transformToXML() take the attribute into account.


Transform to URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transform to URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToUri — Transform to URI

Description

public XSLTProcessor::transformToUri(object $document, string $uri): int

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parameters

document

The DOMDocument or SimpleXMLElement object to be transformed.

uri

The target URI for the transformation.

Return Values

Returns the number of bytes written or false if an error occurred.

Examples

Example #1 Transforming to a HTML file

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

See Also

  • XSLTProcessor::transformToDoc() - Transform to a document
  • XSLTProcessor::transformToXml() - Transform to XML

User Contributed Notes

jonbarnett at gmail dot com 13-Jul-2007 12:32
Sometimes you don't want to transform to a file, an XML string (because you're using text or html), or a DOMDocument.

To transform to standard output, you can use php://output

<?php
$proc->transformToURI($xml, 'php://output');
?>

To transform to a string (of HTML or text, instead of XML), you can use the above in conjunction with output buffering.
<?php
ob_start();
$proc->transformToURI($xml, 'php://output');
$outputString = ob_get_flush();
?>


Transform to XML

  • « XSLTProcessor::transformToUri
  • GUI Extensions »
  • PHP Manual
  • XSLTProcessor
  • Transform to XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transform to XML

Description

public XSLTProcessor::transformToXml(object $document): string|null|false

Transforms the source node to a string applying the stylesheet given by the xsltprocessor::importStylesheet() method.

Parameters

document

The DOMDocument or SimpleXMLElement object to be transformed.

Return Values

The result of the transformation as a string or false on error.

Examples

Example #1 Transforming to a string

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

?>

The above example will output:

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>

See Also

  • XSLTProcessor::transformToDoc() - Transform to a document
  • XSLTProcessor::transformToUri() - Transform to 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=UTF-8">

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 Extensions

  • UI
    • Introduction
    • Installing/Configuring
    • 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 Functions
    • UI\Draw\Text\Font\Weight — Font Weight Settings
    • UI\Draw\Text\Font\Italic — Italic Font Settings
    • UI\Draw\Text\Font\Stretch — Font Stretch Settings
    • UI\Draw\Line\Cap — Line Cap Settings
    • UI\Draw\Line\Join — Line Join Settings
    • UI\Key — Key Identifiers
    • UI\Exception\InvalidArgumentException — InvalidArgumentException
    • UI\Exception\RuntimeException — RuntimeException

User Contributed Notes

There are no user contributed notes for this page.


UI

  • Introduction
  • Installing/Configuring
    • Requirements
    • 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 Functions
    • 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.


Introduction

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.


Installing/Configuring

Table of Contents

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


Requirements

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

This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/ui.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

Introduction

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Class synopsis

final class UI\Point {
/* Properties */
public $x;
public $y;
/* Constructor */
public __construct(float $x, float $y)
/* Methods */
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)
}

Properties

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Table of Contents

  • UI\Point::at — Size Coercion
  • UI\Point::__construct — Construct a new Point
  • UI\Point::getX — Retrieves X
  • UI\Point::getY — Retrieves Y
  • UI\Point::setX — Set X
  • UI\Point::setY — Set Y

User Contributed Notes

There are no user contributed notes for this page.


Size Coercion

  • « UI\Point
  • UI\Point::__construct »
  • PHP Manual
  • UI\Point
  • Size Coercion

UI\Point::at

(UI 1.0.2)

UI\Point::at — Size Coercion

Description

public static UI\Point::at(float $point): UI\Point
public static UI\Point::at(UI\Size $size): UI\Point

Shall return a UI\Point object where x and y are equal to those supplied, either in float or UI\Size form

Parameters

point

The value for x and y

size

The Size to convert

Return Values

The resulting Point

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Point

  • « UI\Point::at
  • UI\Point::getX »
  • PHP Manual
  • UI\Point
  • Construct a new Point

UI\Point::__construct

(UI 0.9.9)

UI\Point::__construct — Construct a new Point

Description

public UI\Point::__construct(float $x, float $y)

Construct a new Point using new co-ordinates

Parameters

x

The new X co-ordinate

y

The new Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves X

  • « UI\Point::__construct
  • UI\Point::getY »
  • PHP Manual
  • UI\Point
  • Retrieves X

UI\Point::getX

(UI 0.9.9)

UI\Point::getX — Retrieves X

Description

public UI\Point::getX(): float

Retrieves the X co-ordinate

Parameters

This function has no parameters.

Return Values

The current X co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Y

  • « UI\Point::getX
  • UI\Point::setX »
  • PHP Manual
  • UI\Point
  • Retrieves Y

UI\Point::getY

(UI 0.9.9)

UI\Point::getY — Retrieves Y

Description

public UI\Point::getY(): float

Retrieves the Y co-ordinate

Parameters

This function has no parameters.

Return Values

The current Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Set X

  • « UI\Point::getY
  • UI\Point::setY »
  • PHP Manual
  • UI\Point
  • Set X

UI\Point::setX

(UI 0.9.9)

UI\Point::setX — Set X

Description

public UI\Point::setX(float $point)

Set the X co-ordinate

Parameters

point

The new X co-ordinate

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set Y

  • « UI\Point::setX
  • UI\Size »
  • PHP Manual
  • UI\Point
  • Set Y

UI\Point::setY

(UI 0.9.9)

UI\Point::setY — Set Y

Description

public UI\Point::setY(float $point)

Set the Y co-ordinate

Parameters

point

The new Y co-ordinate

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Represents dimensions (width, height)

(UI 0.9.9)

Introduction

Sizes are used throughout UI to represent the size of a screen, control, or area.

Class synopsis

final class UI\Size {
/* Properties */
public $width;
public $height;
/* Constructor */
public __construct(float $width, float $height)
/* Methods */
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)
}

Properties

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Table of Contents

  • UI\Size::__construct — Construct a new Size
  • UI\Size::getHeight — Retrieves Height
  • UI\Size::getWidth — Retrives Width
  • UI\Size::of — Point Coercion
  • UI\Size::setHeight — Set Height
  • UI\Size::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Size

  • « UI\Size
  • UI\Size::getHeight »
  • PHP Manual
  • UI\Size
  • Construct a new Size

UI\Size::__construct

(UI 0.9.9)

UI\Size::__construct — Construct a new Size

Description

public UI\Size::__construct(float $width, float $height)

Construct a new Size using new width and height

Parameters

width

The new width

height

The new height

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Height

  • « UI\Size::__construct
  • UI\Size::getWidth »
  • PHP Manual
  • UI\Size
  • Retrieves Height

UI\Size::getHeight

(UI 0.9.9)

UI\Size::getHeight — Retrieves Height

Description

public UI\Size::getHeight(): float

Retrieves the Height

Parameters

This function has no parameters.

Return Values

The current Height

User Contributed Notes

There are no user contributed notes for this page.


Retrives Width

  • « UI\Size::getHeight
  • UI\Size::of »
  • PHP Manual
  • UI\Size
  • Retrives Width

UI\Size::getWidth

(UI 0.9.9)

UI\Size::getWidth — Retrives Width

Description

public UI\Size::getWidth(): float

Retrieves the Width

Parameters

This function has no parameters.

Return Values

The current Width

User Contributed Notes

There are no user contributed notes for this page.


Point Coercion

  • « UI\Size::getWidth
  • UI\Size::setHeight »
  • PHP Manual
  • UI\Size
  • Point Coercion

UI\Size::of

(UI 1.0.2)

UI\Size::of — Point Coercion

Description

public static UI\Size::of(float $size): UI\Size
public static UI\Size::of(UI\Point $point): UI\Size

Shall return a UI\Size object where width and height are equal to those supplied, either in float or UI\Point form

Parameters

size

The value for width and height

point

The Point to convert

Return Values

The resulting Size

User Contributed Notes

There are no user contributed notes for this page.


Set Height

  • « UI\Size::of
  • UI\Size::setWidth »
  • PHP Manual
  • UI\Size
  • Set Height

UI\Size::setHeight

(UI 0.9.9)

UI\Size::setHeight — Set Height

Description

public UI\Size::setHeight(float $size)

Set new Height

Parameters

size

The new Height

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • « UI\Size::setHeight
  • UI\Window »
  • PHP Manual
  • UI\Size
  • Set Width

UI\Size::setWidth

(UI 0.9.9)

UI\Size::setWidth — Set Width

Description

public UI\Size::setWidth(float $size)

Set new Width

Parameters

size

The new Width

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

Introduction

Represents a UI Window

Class synopsis

class UI\Window extends UI\Control {
/* Properties */
protected $controls;
/* Constructor */
public __construct(string $title, Size $size, bool $menu = false)
/* Methods */
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)
/* Inherited methods */
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()
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • 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

Description

public UI\Window::add(UI\Control $control)

Shall add a Control to this Window

Parameters

control

The Control to add

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Window

  • « UI\Window::add
  • UI\Window::error »
  • PHP Manual
  • UI\Window
  • Construct a new Window

UI\Window::__construct

(UI 0.9.9)

UI\Window::__construct — Construct a new Window

Description

public UI\Window::__construct(string $title, Size $size, bool $menu = false)

Shall construct a new Window

Parameters

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

Description

public UI\Window::error(string $title, string $msg)

Shall show an error box

Parameters

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

Description

public UI\Window::getSize(): UI\Size

Shall return the size of this Window

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get Title

  • « UI\Window::getSize
  • UI\Window::hasBorders »
  • PHP Manual
  • UI\Window
  • Get Title

UI\Window::getTitle

(UI 0.9.9)

UI\Window::getTitle — Get Title

Description

public UI\Window::getTitle(): string

Shall retrieve the title of this Window

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Border Detection

  • « UI\Window::getTitle
  • UI\Window::hasMargin »
  • PHP Manual
  • UI\Window
  • Border Detection

UI\Window::hasBorders

(UI 0.9.9)

UI\Window::hasBorders — Border Detection

Description

public UI\Window::hasBorders(): bool

Shall detect if borders are used on this Window

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • « UI\Window::hasBorders
  • UI\Window::isFullScreen »
  • PHP Manual
  • UI\Window
  • Margin Detection

UI\Window::hasMargin

(UI 0.9.9)

UI\Window::hasMargin — Margin Detection

Description

public UI\Window::hasMargin(): bool

Shall detect if margins are used on this Window

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Detection

  • « UI\Window::hasMargin
  • UI\Window::msg »
  • PHP Manual
  • UI\Window
  • Full Screen Detection

UI\Window::isFullScreen

(UI 0.9.9)

UI\Window::isFullScreen — Full Screen Detection

Description

public UI\Window::isFullScreen(): bool

Shall detect if this Window us using the whole screen

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Show Message Box

  • « UI\Window::isFullScreen
  • UI\Window::onClosing »
  • PHP Manual
  • UI\Window
  • Show Message Box

UI\Window::msg

(UI 0.9.9)

UI\Window::msg — Show Message Box

Description

public UI\Window::msg(string $title, string $msg)

Shall show a message box

Parameters

title

The title of the message box

msg

The message

User Contributed Notes

There are no user contributed notes for this page.


Closing Callback

  • « UI\Window::msg
  • UI\Window::open »
  • PHP Manual
  • UI\Window
  • Closing Callback

UI\Window::onClosing

(UI 0.9.9)

UI\Window::onClosing — Closing Callback

Description

protected UI\Window::onClosing(): int

Should gracefully destroy this Window

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Open Dialog

  • « UI\Window::onClosing
  • UI\Window::save »
  • PHP Manual
  • UI\Window
  • Open Dialog

UI\Window::open

(UI 0.9.9)

UI\Window::open — Open Dialog

Description

public UI\Window::open(): string

Shall show an open file dialog

Parameters

This function has no parameters.

Return Values

Returns the name of the file selected for opening

User Contributed Notes

There are no user contributed notes for this page.


Save Dialog

  • « UI\Window::open
  • UI\Window::setBorders »
  • PHP Manual
  • UI\Window
  • Save Dialog

UI\Window::save

(UI 0.9.9)

UI\Window::save — Save Dialog

Description

public UI\Window::save(): string

Shall show a save dialog

Parameters

This function has no parameters.

Return Values

Returns the file name selecting for saving

User Contributed Notes

There are no user contributed notes for this page.


Border Use

  • « UI\Window::save
  • UI\Window::setFullScreen »
  • PHP Manual
  • UI\Window
  • Border Use

UI\Window::setBorders

(UI 0.9.9)

UI\Window::setBorders — Border Use

Description

public UI\Window::setBorders(bool $borders)

Shall enable or disable the use of borders on this Window

Parameters

borders

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Use

  • « UI\Window::setBorders
  • UI\Window::setMargin »
  • PHP Manual
  • UI\Window
  • Full Screen Use

UI\Window::setFullScreen

(UI 0.9.9)

UI\Window::setFullScreen — Full Screen Use

Description

public UI\Window::setFullScreen(bool $full)

Shall enable or disable the use of the full screen for this Window

Warning

This function is currently not documented; only its argument list is available.

Parameters

full

User Contributed Notes

There are no user contributed notes for this page.


Margin Use

  • « UI\Window::setFullScreen
  • UI\Window::setSize »
  • PHP Manual
  • UI\Window
  • Margin Use

UI\Window::setMargin

(UI 0.9.9)

UI\Window::setMargin — Margin Use

Description

public UI\Window::setMargin(bool $margin)

Shall enable or disable the use of margins for this Window

Parameters

margin

User Contributed Notes

There are no user contributed notes for this page.


Set Size

  • « UI\Window::setMargin
  • UI\Window::setTitle »
  • PHP Manual
  • UI\Window
  • Set Size

UI\Window::setSize

(UI 0.9.9)

UI\Window::setSize — Set Size

Description

public UI\Window::setSize(UI\Size $size)

Shall set the size of this Window

Parameters

size

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Window Title

  • « UI\Window::setSize
  • UI\Control »
  • PHP Manual
  • UI\Window
  • Window Title

UI\Window::setTitle

(UI 0.9.9)

UI\Window::setTitle — Window Title

Description

public UI\Window::setTitle(string $title)

Shall set the title for this Window

Parameters

title

The new title

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

Introduction

This is the closed base class for all UI Controls.

Class synopsis

final class UI\Control {
/* Methods */
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()
}

Table of Contents

  • UI\Control::destroy — Destroy Control
  • UI\Control::disable — Disable Control
  • UI\Control::enable — Enable Control
  • UI\Control::getParent — Get Parent Control
  • UI\Control::getTopLevel — Get Top Level
  • UI\Control::hide — Hide Control
  • UI\Control::isEnabled — Determine if Control is enabled
  • UI\Control::isVisible — Determine if Control is visible
  • UI\Control::setParent — Set Parent Control
  • UI\Control::show — Control Show

User Contributed Notes

There are no user contributed notes for this page.


Destroy Control

  • « UI\Control
  • UI\Control::disable »
  • PHP Manual
  • UI\Control
  • Destroy Control

UI\Control::destroy

(UI 0.9.9)

UI\Control::destroy — Destroy Control

Description

public UI\Control::destroy()

Shall destroy this Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Disable Control

  • « UI\Control::destroy
  • UI\Control::enable »
  • PHP Manual
  • UI\Control
  • Disable Control

UI\Control::disable

(UI 0.9.9)

UI\Control::disable — Disable Control

Description

public UI\Control::disable()

Shall disable this Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Enable Control

  • « UI\Control::disable
  • UI\Control::getParent »
  • PHP Manual
  • UI\Control
  • Enable Control

UI\Control::enable

(UI 0.9.9)

UI\Control::enable — Enable Control

Description

public UI\Control::enable()

Shall enable this Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get Parent Control

  • « UI\Control::enable
  • UI\Control::getTopLevel »
  • PHP Manual
  • UI\Control
  • Get Parent Control

UI\Control::getParent

(UI 0.9.9)

UI\Control::getParent — Get Parent Control

Description

public UI\Control::getParent(): UI\Control

Shall return the parent Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Get Top Level

  • « UI\Control::getParent
  • UI\Control::hide »
  • PHP Manual
  • UI\Control
  • Get Top Level

UI\Control::getTopLevel

(UI 0.9.9)

UI\Control::getTopLevel — Get Top Level

Description

public UI\Control::getTopLevel(): int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Hide Control

  • « UI\Control::getTopLevel
  • UI\Control::isEnabled »
  • PHP Manual
  • UI\Control
  • Hide Control

UI\Control::hide

(UI 0.9.9)

UI\Control::hide — Hide Control

Description

public UI\Control::hide()

Shall hide this Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Determine if Control is enabled

  • « UI\Control::hide
  • UI\Control::isVisible »
  • PHP Manual
  • UI\Control
  • Determine if Control is enabled

UI\Control::isEnabled

(UI 0.9.9)

UI\Control::isEnabled — Determine if Control is enabled

Description

public UI\Control::isEnabled(): bool

Shall detect if this Control is enabled

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Determine if Control is visible

  • « UI\Control::isEnabled
  • UI\Control::setParent »
  • PHP Manual
  • UI\Control
  • Determine if Control is visible

UI\Control::isVisible

(UI 0.9.9)

UI\Control::isVisible — Determine if Control is visible

Description

public UI\Control::isVisible(): bool

Shall detect if this Control is visible

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set Parent Control

  • « UI\Control::isVisible
  • UI\Control::show »
  • PHP Manual
  • UI\Control
  • Set Parent Control

UI\Control::setParent

(UI 0.9.9)

UI\Control::setParent — Set Parent Control

Description

public UI\Control::setParent(UI\Control $parent)

Shall set the parent Control of this Control

Parameters

parent

The parent Control

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Control Show

  • « UI\Control::setParent
  • UI\Menu »
  • PHP Manual
  • UI\Control
  • Control Show

UI\Control::show

(UI 0.9.9)

UI\Control::show — Control Show

Description

public UI\Control::show()

Shall show this Control

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

Introduction

Menus must be constructed before the first Window, and can be shown on any Window

Class synopsis

class UI\Menu {
/* Constructor */
public __construct(string $name)
/* Methods */
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()
}

Table of Contents

  • UI\Menu::append — Append Menu Item
  • UI\Menu::appendAbout — Append About Menu Item
  • UI\Menu::appendCheck — Append Checkable Menu Item
  • UI\Menu::appendPreferences — Append Preferences Menu Item
  • UI\Menu::appendQuit — Append Quit Menu Item
  • UI\Menu::appendSeparator — Append Menu Item Separator
  • UI\Menu::__construct — Construct a new Menu

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item

  • « UI\Menu
  • UI\Menu::appendAbout »
  • PHP Manual
  • UI\Menu
  • Append Menu Item

UI\Menu::append

(UI 0.9.9)

UI\Menu::append — Append Menu Item

Description

public UI\Menu::append(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a new Menu Item

Parameters

name

The name (text) for the new item

type

The type for the new item

Return Values

A constructed object of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append About Menu Item

  • « UI\Menu::append
  • UI\Menu::appendCheck »
  • PHP Manual
  • UI\Menu
  • Append About Menu Item

UI\Menu::appendAbout

(UI 0.9.9)

UI\Menu::appendAbout — Append About Menu Item

Description

public UI\Menu::appendAbout(string $type = UI\MenuItem::class): UI\MenuItem

Shall append an About menu item

Parameters

type

The type for the new item

Return Values

A constructed About menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Checkable Menu Item

  • « UI\Menu::appendAbout
  • UI\Menu::appendPreferences »
  • PHP Manual
  • UI\Menu
  • Append Checkable Menu Item

UI\Menu::appendCheck

(UI 0.9.9)

UI\Menu::appendCheck — Append Checkable Menu Item

Description

public UI\Menu::appendCheck(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a checkable menu item

Parameters

name

The name (text) for the new item

type

The type for the new item

Return Values

A constructed checkable menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Preferences Menu Item

  • « UI\Menu::appendCheck
  • UI\Menu::appendQuit »
  • PHP Manual
  • UI\Menu
  • Append Preferences Menu Item

UI\Menu::appendPreferences

(UI 0.9.9)

UI\Menu::appendPreferences — Append Preferences Menu Item

Description

public UI\Menu::appendPreferences(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Preferences menu item

Parameters

type

The type for the new item

Return Values

A constructed Preferences menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Quit Menu Item

  • « UI\Menu::appendPreferences
  • UI\Menu::appendSeparator »
  • PHP Manual
  • UI\Menu
  • Append Quit Menu Item

UI\Menu::appendQuit

(UI 0.9.9)

UI\Menu::appendQuit — Append Quit Menu Item

Description

public UI\Menu::appendQuit(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Quit menu item

Parameters

type

The type for the new item

Return Values

A constructed Quit menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item Separator

  • « UI\Menu::appendQuit
  • UI\Menu::__construct »
  • PHP Manual
  • UI\Menu
  • Append Menu Item Separator

UI\Menu::appendSeparator

(UI 0.9.9)

UI\Menu::appendSeparator — Append Menu Item Separator

Description

public UI\Menu::appendSeparator()

Shall append a separator

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Menu

  • « UI\Menu::appendSeparator
  • UI\MenuItem »
  • PHP Manual
  • UI\Menu
  • Construct a new Menu

UI\Menu::__construct

(UI 0.9.9)

UI\Menu::__construct — Construct a new Menu

Description

public UI\Menu::__construct(string $name)

Shall construct a new Menu

Parameters

name

The name (text) for the menu

User Contributed Notes

There are no user contributed notes for this page.


Menu Item

(UI 0.9.9)

Introduction

Menu Items should only be created by the Menu

Class synopsis

class UI\MenuItem {
/* Methods */
public disable()
public enable()
public isChecked(): bool
protected onClick()
public setChecked(bool $checked)
}

Table of Contents

  • UI\MenuItem::disable — Disable Menu Item
  • UI\MenuItem::enable — Enable Menu Item
  • UI\MenuItem::isChecked — Detect Checked
  • UI\MenuItem::onClick — On Click Callback
  • UI\MenuItem::setChecked — Set Checked

User Contributed Notes

There are no user contributed notes for this page.


Disable Menu Item

  • « UI\MenuItem
  • UI\MenuItem::enable »
  • PHP Manual
  • UI\MenuItem
  • Disable Menu Item

UI\MenuItem::disable

(UI 0.9.9)

UI\MenuItem::disable — Disable Menu Item

Description

public UI\MenuItem::disable()

Shall disable this Menu Item

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Enable Menu Item

  • « UI\MenuItem::disable
  • UI\MenuItem::isChecked »
  • PHP Manual
  • UI\MenuItem
  • Enable Menu Item

UI\MenuItem::enable

(UI 0.9.9)

UI\MenuItem::enable — Enable Menu Item

Description

public UI\MenuItem::enable()

Shall enable this Menu Item

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Detect Checked

  • « UI\MenuItem::enable
  • UI\MenuItem::onClick »
  • PHP Manual
  • UI\MenuItem
  • Detect Checked

UI\MenuItem::isChecked

(UI 0.9.9)

UI\MenuItem::isChecked — Detect Checked

Description

public UI\MenuItem::isChecked(): bool

Shall detect if this Menu Item is checked

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


On Click Callback

  • « UI\MenuItem::isChecked
  • UI\MenuItem::setChecked »
  • PHP Manual
  • UI\MenuItem
  • On Click Callback

UI\MenuItem::onClick

(UI 0.9.9)

UI\MenuItem::onClick — On Click Callback

Description

protected UI\MenuItem::onClick()

Shall be executed when this Menu Item is clicked

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Checked

  • « UI\MenuItem::onClick
  • UI\Area »
  • PHP Manual
  • UI\MenuItem
  • Set Checked

UI\MenuItem::setChecked

(UI 0.9.9)

UI\MenuItem::setChecked — Set Checked

Description

public UI\MenuItem::setChecked(bool $checked)

Shall set the checked status of this Menu Item

Parameters

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

Introduction

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Class synopsis

class UI\Area extends UI\Control {
/* Constants */
const int Ctrl;
const int Alt;
const int Shift;
const int Super;
const int Down;
const int Up;
/* Methods */
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)
/* Inherited methods */
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()
}

Predefined Constants

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

Table of Contents

  • UI\Area::onDraw — Draw Callback
  • UI\Area::onKey — Key Callback
  • UI\Area::onMouse — Mouse Callback
  • UI\Area::redraw — Redraw Area
  • UI\Area::scrollTo — Area Scroll
  • UI\Area::setSize — Set Size

User Contributed Notes

There are no user contributed notes for this page.


Draw Callback

  • « UI\Area
  • UI\Area::onKey »
  • PHP Manual
  • UI\Area
  • Draw Callback

UI\Area::onDraw

(UI 0.9.9)

UI\Area::onDraw — Draw Callback

Description

protected UI\Area::onDraw(
UI\Draw\Pen $pen,
UI\Size $areaSize,
UI\Point $clipPoint,
UI\Size $clipSize
)

Shall be invoked when this Area requires redrawing

Parameters

pen

A Pen suitable for drawing in this Area

areaSize

The size of the Area

clipPoint

The clip point of the Area

clipSize

The clip size of the Area

User Contributed Notes

There are no user contributed notes for this page.


Key Callback

  • « UI\Area::onDraw
  • UI\Area::onMouse »
  • PHP Manual
  • UI\Area
  • Key Callback

UI\Area::onKey

(UI 0.9.9)

UI\Area::onKey — Key Callback

Description

protected UI\Area::onKey(string $key, int $ext, int $flags)

Shall be executed on key events

Parameters

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Mouse Callback

  • « UI\Area::onKey
  • UI\Area::redraw »
  • PHP Manual
  • UI\Area
  • Mouse Callback

UI\Area::onMouse

(UI 0.9.9)

UI\Area::onMouse — Mouse Callback

Description

protected UI\Area::onMouse(UI\Point $areaPoint, UI\Size $areaSize, int $flags)

Shall be executed on mouse events

Parameters

areaPoint

The co-ordinates of the event

areaSize

The size of the area of the event

flags

Event modifiers

User Contributed Notes

There are no user contributed notes for this page.


Redraw Area

  • « UI\Area::onMouse
  • UI\Area::scrollTo »
  • PHP Manual
  • UI\Area
  • Redraw Area

UI\Area::redraw

(UI 0.9.9)

UI\Area::redraw — Redraw Area

Description

public UI\Area::redraw()

Requests that this Area is redrawn

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Area Scroll

  • « UI\Area::redraw
  • UI\Area::setSize »
  • PHP Manual
  • UI\Area
  • Area Scroll

UI\Area::scrollTo

(UI 0.9.9)

UI\Area::scrollTo — Area Scroll

Description

public UI\Area::scrollTo(UI\Point $point, UI\Size $size)

Scroll this Area

Parameters

point

The point to scroll to

size

The size of the scroll pane

User Contributed Notes

There are no user contributed notes for this page.


Set Size

  • « UI\Area::scrollTo
  • UI\Executor »
  • PHP Manual
  • UI\Area
  • Set Size

UI\Area::setSize

(UI 0.9.9)

UI\Area::setSize — Set Size

Description

public UI\Area::setSize(UI\Size $size)

Sets the size of this Area

Parameters

size

The new size

User Contributed Notes

There are no user contributed notes for this page.


Execution Scheduler

(UI 2.0.0)

Introduction

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Class synopsis

abstract class UI\Executor {
/* Constructor */
public __construct()
public __construct(int $microseconds)
public __construct(int $seconds, int $microseconds)
/* Methods */
public kill(): void
abstract protected onExecute(): void
public setInterval(int $microseconds): bool
public setInterval(int $seconds, int $microseconds): bool
}

Table of Contents

  • UI\Executor::__construct — Construct a new Executor
  • UI\Executor::kill — Stop Executor
  • UI\Executor::onExecute — Execution Callback
  • UI\Executor::setInterval — Interval Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Executor

  • « UI\Executor
  • UI\Executor::kill »
  • PHP Manual
  • UI\Executor
  • Construct a new Executor

UI\Executor::__construct

(UI 2.0.0)

UI\Executor::__construct — Construct a new Executor

Description

public UI\Executor::__construct()
public UI\Executor::__construct(int $microseconds)
public UI\Executor::__construct(int $seconds, int $microseconds)

Shall construct an executor with the given interval, will not start executing until main loop is entered

Parameters

seconds

Seconds between executions

microseconds

Microseconds between executions

User Contributed Notes

There are no user contributed notes for this page.


Stop Executor

  • « UI\Executor::__construct
  • UI\Executor::onExecute »
  • PHP Manual
  • UI\Executor
  • Stop Executor

UI\Executor::kill

(UI 2.0.0)

UI\Executor::kill — Stop Executor

Description

public UI\Executor::kill(): void

Shall stop an executor, the executor cannot be restarted

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Execution Callback

  • « UI\Executor::kill
  • UI\Executor::setInterval »
  • PHP Manual
  • UI\Executor
  • Execution Callback

UI\Executor::onExecute

(UI 2.0.0)

UI\Executor::onExecute — Execution Callback

Description

abstract protected UI\Executor::onExecute(): void

Shall be repetitively queued for execution in the main thread

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Interval Manipulation

  • « UI\Executor::onExecute
  • UI\Controls\Tab »
  • PHP Manual
  • UI\Executor
  • Interval Manipulation

UI\Executor::setInterval

(UI 2.0.0)

UI\Executor::setInterval — Interval Manipulation

Description

public UI\Executor::setInterval(int $microseconds): bool
public UI\Executor::setInterval(int $seconds, int $microseconds): bool

Shall set the new interval. An interval of 0 will pause the executor until a new interval has been set

Parameters

seconds

microseconds

Return Values

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

Introduction

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Class synopsis

class UI\Controls\Tab extends UI\Control {
/* Properties */
protected $controls;
/* Methods */
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)
/* Inherited methods */
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()
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Tab::append — Append Page
  • UI\Controls\Tab::delete — Delete Page
  • UI\Controls\Tab::hasMargin — Margin Detection
  • UI\Controls\Tab::insertAt — Insert Page
  • UI\Controls\Tab::pages — Page Count
  • UI\Controls\Tab::setMargin — Set Margin

User Contributed Notes

There are no user contributed notes for this page.


Append Page

  • « UI\Controls\Tab
  • UI\Controls\Tab::delete »
  • PHP Manual
  • UI\Controls\Tab
  • Append Page

UI\Controls\Tab::append

(UI 0.9.9)

UI\Controls\Tab::append — Append Page

Description

public UI\Controls\Tab::append(string $name, UI\Control $control): int

Append a new page to this Tab

Parameters

name

The name for the new page

control

The control for the new page

Return Values

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Delete Page

  • « UI\Controls\Tab::append
  • UI\Controls\Tab::hasMargin »
  • PHP Manual
  • UI\Controls\Tab
  • Delete Page

UI\Controls\Tab::delete

(UI 0.9.9)

UI\Controls\Tab::delete — Delete Page

Description

public UI\Controls\Tab::delete(int $index): bool

Shall remove the selected page from this Tab

Parameters

index

The index of the page to remove

Return Values

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • « UI\Controls\Tab::delete
  • UI\Controls\Tab::insertAt »
  • PHP Manual
  • UI\Controls\Tab
  • Margin Detection

UI\Controls\Tab::hasMargin

(UI 0.9.9)

UI\Controls\Tab::hasMargin — Margin Detection

Description

public UI\Controls\Tab::hasMargin(int $page): bool

Shall detect if the given page has a margin.

Parameters

page

The index of the page

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Insert Page

  • « UI\Controls\Tab::hasMargin
  • UI\Controls\Tab::pages »
  • PHP Manual
  • UI\Controls\Tab
  • Insert Page

UI\Controls\Tab::insertAt

(UI 0.9.9)

UI\Controls\Tab::insertAt — Insert Page

Description

public UI\Controls\Tab::insertAt(string $name, int $page, UI\Control $control)

Shall insert a new page into this Tab

Parameters

name

The name for the new page

page

The index to perform the insertion before

control

The control for the new page

User Contributed Notes

There are no user contributed notes for this page.


Page Count

  • « UI\Controls\Tab::insertAt
  • UI\Controls\Tab::setMargin »
  • PHP Manual
  • UI\Controls\Tab
  • Page Count

UI\Controls\Tab::pages

(UI 0.9.9)

UI\Controls\Tab::pages — Page Count

Description

public UI\Controls\Tab::pages(): int

Shall return the number of pages in this Tab

Parameters

This function has no parameters.

Return Values

The number of pages in this Tab

User Contributed Notes

There are no user contributed notes for this page.


Set Margin

  • « UI\Controls\Tab::pages
  • UI\Controls\Check »
  • PHP Manual
  • UI\Controls\Tab
  • Set Margin

UI\Controls\Tab::setMargin

(UI 0.9.9)

UI\Controls\Tab::setMargin — Set Margin

Description

public UI\Controls\Tab::setMargin(int $page, bool $margin)

Shall enable or disable margins on the selected page

Parameters

page

The page to select

margin

Margin switch

User Contributed Notes

There are no user contributed notes for this page.


Check Control

(UI 0.9.9)

Introduction

A Check is a labelled checkable box

Class synopsis

class UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methods */
public getText(): string
public isChecked(): bool
protected onToggle()
public setChecked(bool $checked)
public setText(string $text)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Check::__construct — Construct a new Check
  • UI\Controls\Check::getText — Get Text
  • UI\Controls\Check::isChecked — Checked Detection
  • UI\Controls\Check::onToggle — Toggle Callback
  • UI\Controls\Check::setChecked — Set Checked
  • UI\Controls\Check::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Check

  • « UI\Controls\Check
  • UI\Controls\Check::getText »
  • PHP Manual
  • UI\Controls\Check
  • Construct a new Check

UI\Controls\Check::__construct

(UI 0.9.9)

UI\Controls\Check::__construct — Construct a new Check

Description

public UI\Controls\Check::__construct(string $text)

Shall construct a new Check

Parameters

text

The text (label) for the Check box

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\Check::__construct
  • UI\Controls\Check::isChecked »
  • PHP Manual
  • UI\Controls\Check
  • Get Text

UI\Controls\Check::getText

(UI 0.9.9)

UI\Controls\Check::getText — Get Text

Description

public UI\Controls\Check::getText(): string

Shall return the text (label) for this Check

Parameters

This function has no parameters.

Return Values

The current text (label)

User Contributed Notes

There are no user contributed notes for this page.


Checked Detection

  • « UI\Controls\Check::getText
  • UI\Controls\Check::onToggle »
  • PHP Manual
  • UI\Controls\Check
  • Checked Detection

UI\Controls\Check::isChecked

(UI 0.9.9)

UI\Controls\Check::isChecked — Checked Detection

Description

public UI\Controls\Check::isChecked(): bool

Shall detect the status of this Check

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Toggle Callback

  • « UI\Controls\Check::isChecked
  • UI\Controls\Check::setChecked »
  • PHP Manual
  • UI\Controls\Check
  • Toggle Callback

UI\Controls\Check::onToggle

(UI 0.9.9)

UI\Controls\Check::onToggle — Toggle Callback

Description

protected UI\Controls\Check::onToggle()

Shall be executed when the status of this Check is changed

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Checked

  • « UI\Controls\Check::onToggle
  • UI\Controls\Check::setText »
  • PHP Manual
  • UI\Controls\Check
  • Set Checked

UI\Controls\Check::setChecked

(UI 0.9.9)

UI\Controls\Check::setChecked — Set Checked

Description

public UI\Controls\Check::setChecked(bool $checked)

Shall change the status of this Check

Parameters

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\Check::setChecked
  • UI\Controls\Button »
  • PHP Manual
  • UI\Controls\Check
  • Set Text

UI\Controls\Check::setText

(UI 0.9.9)

UI\Controls\Check::setText — Set Text

Description

public UI\Controls\Check::setText(string $text)

Shall set the text (label) for this Check

Parameters

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


Button Control

(UI 0.9.9)

Introduction

Represents a labelled clickable button

Class synopsis

class UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methods */
public getText(): string
protected onClick()
public setText(string $text)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Button::__construct — Construct a new Button
  • UI\Controls\Button::getText — Get Text
  • UI\Controls\Button::onClick — Click Handler
  • UI\Controls\Button::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Button

  • « UI\Controls\Button
  • UI\Controls\Button::getText »
  • PHP Manual
  • UI\Controls\Button
  • Construct a new Button

UI\Controls\Button::__construct

(UI 0.9.9)

UI\Controls\Button::__construct — Construct a new Button

Description

public UI\Controls\Button::__construct(string $text)

Shall construct a new Button

Parameters

text

The text (label) for this Button

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\Button::__construct
  • UI\Controls\Button::onClick »
  • PHP Manual
  • UI\Controls\Button
  • Get Text

UI\Controls\Button::getText

(UI 0.9.9)

UI\Controls\Button::getText — Get Text

Description

public UI\Controls\Button::getText(): string

Shall retrieve the text (label) for this Button

Parameters

This function has no parameters.

Return Values

The current text (label)

User Contributed Notes

There are no user contributed notes for this page.


Click Handler

  • « UI\Controls\Button::getText
  • UI\Controls\Button::setText »
  • PHP Manual
  • UI\Controls\Button
  • Click Handler

UI\Controls\Button::onClick

(UI 0.9.9)

UI\Controls\Button::onClick — Click Handler

Description

protected UI\Controls\Button::onClick()

Shall be executed when this Button is clicked

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\Button::onClick
  • UI\Controls\ColorButton »
  • PHP Manual
  • UI\Controls\Button
  • Set Text

UI\Controls\Button::setText

(UI 0.9.9)

UI\Controls\Button::setText — Set Text

Description

public UI\Controls\Button::setText(string $text)

Shall set the text (label) for this Button

Parameters

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


ColorButton Control

(UI 0.9.9)

Introduction

A Color Button is a button which displays a color picker when clicked

Class synopsis

class UI\Controls\ColorButton extends UI\Control {
/* Methods */
public getColor(): UI\Color
protected onChange()
public setColor(UI\Draw\Color $color)
public setColor(int $color)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\ColorButton::getColor — Get Color
  • UI\Controls\ColorButton::onChange — Change Handler
  • UI\Controls\ColorButton::setColor — Set Color

User Contributed Notes

There are no user contributed notes for this page.


Get Color

  • « UI\Controls\ColorButton
  • UI\Controls\ColorButton::onChange »
  • PHP Manual
  • UI\Controls\ColorButton
  • Get Color

UI\Controls\ColorButton::getColor

(UI 0.9.9)

UI\Controls\ColorButton::getColor — Get Color

Description

public UI\Controls\ColorButton::getColor(): UI\Color

Shall retrieve the currently selected Color

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\ColorButton::getColor
  • UI\Controls\ColorButton::setColor »
  • PHP Manual
  • UI\Controls\ColorButton
  • Change Handler

UI\Controls\ColorButton::onChange

(UI 0.9.9)

UI\Controls\ColorButton::onChange — Change Handler

Description

protected UI\Controls\ColorButton::onChange()

Shall be executed when the selected Color is changed

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • « UI\Controls\ColorButton::onChange
  • UI\Controls\Label »
  • PHP Manual
  • UI\Controls\ColorButton
  • Set Color

UI\Controls\ColorButton::setColor

(UI 0.9.9)

UI\Controls\ColorButton::setColor — Set Color

Description

public UI\Controls\ColorButton::setColor(UI\Draw\Color $color)
public UI\Controls\ColorButton::setColor(int $color)

Shall set the currently selected Color

Parameters

color

The new color

User Contributed Notes

There are no user contributed notes for this page.


Label Control

(UI 0.9.9)

Introduction

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Class synopsis

class UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Methods */
public getText(): string
public setText(string $text)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Label::__construct — Construct a new Label
  • UI\Controls\Label::getText — Get Text
  • UI\Controls\Label::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Label

  • « UI\Controls\Label
  • UI\Controls\Label::getText »
  • PHP Manual
  • UI\Controls\Label
  • Construct a new Label

UI\Controls\Label::__construct

(UI 0.9.9)

UI\Controls\Label::__construct — Construct a new Label

Description

public UI\Controls\Label::__construct(string $text)

Shall construct a new Label

Parameters

text

The text for this label

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\Label::__construct
  • UI\Controls\Label::setText »
  • PHP Manual
  • UI\Controls\Label
  • Get Text

UI\Controls\Label::getText

(UI 0.9.9)

UI\Controls\Label::getText — Get Text

Description

public UI\Controls\Label::getText(): string

Shall return the current text for this Label

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\Label::getText
  • UI\Controls\Entry »
  • PHP Manual
  • UI\Controls\Label
  • Set Text

UI\Controls\Label::setText

(UI 0.9.9)

UI\Controls\Label::setText — Set Text

Description

public UI\Controls\Label::setText(string $text)

Shall set the text for this Label

Parameters

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Entry Control

(UI 0.9.9)

Introduction

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Class synopsis

class UI\Controls\Entry extends UI\Control {
/* Constants */
const int Normal;
const int Password;
const int Search;
/* Constructor */
public __construct(int $type = UI\Controls\Entry::Normal)
/* Methods */
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Inherited methods */
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()
}

Predefined Constants

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Table of Contents

  • UI\Controls\Entry::__construct — Construct a new Entry
  • UI\Controls\Entry::getText — Get Text
  • UI\Controls\Entry::isReadOnly — Detect Read Only
  • UI\Controls\Entry::onChange — Change Handler
  • UI\Controls\Entry::setReadOnly — Set Read Only
  • UI\Controls\Entry::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Entry

  • « UI\Controls\Entry
  • UI\Controls\Entry::getText »
  • PHP Manual
  • UI\Controls\Entry
  • Construct a new Entry

UI\Controls\Entry::__construct

(UI 0.9.9)

UI\Controls\Entry::__construct — Construct a new Entry

Description

public UI\Controls\Entry::__construct(int $type = UI\Controls\Entry::Normal)

Construct a new entry of the given type

Parameters

type

Entry::Normal, Entry::Password, or Entry::Search

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\Entry::__construct
  • UI\Controls\Entry::isReadOnly »
  • PHP Manual
  • UI\Controls\Entry
  • Get Text

UI\Controls\Entry::getText

(UI 0.9.9)

UI\Controls\Entry::getText — Get Text

Description

public UI\Controls\Entry::getText(): string

Shall return the current text from this Entry

Parameters

This function has no parameters.

Return Values

The current text

User Contributed Notes

There are no user contributed notes for this page.


Detect Read Only

  • « UI\Controls\Entry::getText
  • UI\Controls\Entry::onChange »
  • PHP Manual
  • UI\Controls\Entry
  • Detect Read Only

UI\Controls\Entry::isReadOnly

(UI 0.9.9)

UI\Controls\Entry::isReadOnly — Detect Read Only

Description

public UI\Controls\Entry::isReadOnly(): bool

Shall detect if this Entry is read only

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\Entry::isReadOnly
  • UI\Controls\Entry::setReadOnly »
  • PHP Manual
  • UI\Controls\Entry
  • Change Handler

UI\Controls\Entry::onChange

(UI 0.9.9)

UI\Controls\Entry::onChange — Change Handler

Description

protected UI\Controls\Entry::onChange()

Shall be executed when the text in this Entry changes

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Read Only

  • « UI\Controls\Entry::onChange
  • UI\Controls\Entry::setText »
  • PHP Manual
  • UI\Controls\Entry
  • Set Read Only

UI\Controls\Entry::setReadOnly

(UI 0.9.9)

UI\Controls\Entry::setReadOnly — Set Read Only

Description

public UI\Controls\Entry::setReadOnly(bool $readOnly)

Shall enable or disable read only for this Entry

Parameters

readOnly

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\Entry::setReadOnly
  • UI\Controls\MultilineEntry »
  • PHP Manual
  • UI\Controls\Entry
  • Set Text

UI\Controls\Entry::setText

(UI 0.9.9)

UI\Controls\Entry::setText — Set Text

Description

public UI\Controls\Entry::setText(string $text)

Shall set the text for this Entry

Parameters

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


MultilineEntry Control

(UI 0.9.9)

Introduction

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Class synopsis

class UI\Controls\MultilineEntry extends UI\Control {
/* Constants */
const int Wrap;
const int NoWrap;
/* Constructor */
public __construct(int $type = ?)
/* Methods */
public append(string $text)
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Inherited methods */
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()
}

Predefined Constants

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Table of Contents

  • UI\Controls\MultilineEntry::append — Append Text
  • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
  • UI\Controls\MultilineEntry::getText — Get Text
  • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
  • UI\Controls\MultilineEntry::onChange — Change Handler
  • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
  • UI\Controls\MultilineEntry::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Append Text

  • « UI\Controls\MultilineEntry
  • UI\Controls\MultilineEntry::__construct »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Append Text

UI\Controls\MultilineEntry::append

(UI 0.9.9)

UI\Controls\MultilineEntry::append — Append Text

Description

public UI\Controls\MultilineEntry::append(string $text)

Shall append the given text to the text in this Multiline Entry

Parameters

text

The text to append

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Multiline Entry

  • « UI\Controls\MultilineEntry::append
  • UI\Controls\MultilineEntry::getText »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Construct a new Multiline Entry

UI\Controls\MultilineEntry::__construct

(UI 0.9.9)

UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry

Description

public UI\Controls\MultilineEntry::__construct(int $type = ?)

Shall construct a new Multiline Entry of the given type

Parameters

type

MultilineEntry::Wrap or MultilineEntry::NoWrap

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\MultilineEntry::__construct
  • UI\Controls\MultilineEntry::isReadOnly »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Get Text

UI\Controls\MultilineEntry::getText

(UI 0.9.9)

UI\Controls\MultilineEntry::getText — Get Text

Description

public UI\Controls\MultilineEntry::getText(): string

Shall return the text in this Multiline Entry

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Read Only Detection

  • « UI\Controls\MultilineEntry::getText
  • UI\Controls\MultilineEntry::onChange »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Read Only Detection

UI\Controls\MultilineEntry::isReadOnly

(UI 0.9.9)

UI\Controls\MultilineEntry::isReadOnly — Read Only Detection

Description

public UI\Controls\MultilineEntry::isReadOnly(): bool

Shall detect if this Multiline Entry is read only

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\MultilineEntry::isReadOnly
  • UI\Controls\MultilineEntry::setReadOnly »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Change Handler

UI\Controls\MultilineEntry::onChange

(UI 0.9.9)

UI\Controls\MultilineEntry::onChange — Change Handler

Description

protected UI\Controls\MultilineEntry::onChange()

Shall be executed when the text in this Multiline Entry is changed

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Read Only

  • « UI\Controls\MultilineEntry::onChange
  • UI\Controls\MultilineEntry::setText »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Read Only

UI\Controls\MultilineEntry::setReadOnly

(UI 0.9.9)

UI\Controls\MultilineEntry::setReadOnly — Set Read Only

Description

public UI\Controls\MultilineEntry::setReadOnly(bool $readOnly)

Shall enable or disable read only on this Multiline Entry

Parameters

readOnly

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\MultilineEntry::setReadOnly
  • UI\Controls\Spin »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Text

UI\Controls\MultilineEntry::setText

(UI 0.9.9)

UI\Controls\MultilineEntry::setText — Set Text

Description

public UI\Controls\MultilineEntry::setText(string $text)

Shall set the text in this Multiline Entry

Parameters

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Spin Control

(UI 0.9.9)

Introduction

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Class synopsis

class UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Methods */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Spin::__construct — Construct a new Spin
  • UI\Controls\Spin::getValue — Get Value
  • UI\Controls\Spin::onChange — Change Handler
  • UI\Controls\Spin::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Spin

  • « UI\Controls\Spin
  • UI\Controls\Spin::getValue »
  • PHP Manual
  • UI\Controls\Spin
  • Construct a new Spin

UI\Controls\Spin::__construct

(UI 0.9.9)

UI\Controls\Spin::__construct — Construct a new Spin

Description

public UI\Controls\Spin::__construct(int $min, int $max)

Constructs a new Spin with the given range

Parameters

min

The minimum value allowed

max

The maximum value allowed

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • « UI\Controls\Spin::__construct
  • UI\Controls\Spin::onChange »
  • PHP Manual
  • UI\Controls\Spin
  • Get Value

UI\Controls\Spin::getValue

(UI 0.9.9)

UI\Controls\Spin::getValue — Get Value

Description

public UI\Controls\Spin::getValue(): int

Get the value in this Spin

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\Spin::getValue
  • UI\Controls\Spin::setValue »
  • PHP Manual
  • UI\Controls\Spin
  • Change Handler

UI\Controls\Spin::onChange

(UI 0.9.9)

UI\Controls\Spin::onChange — Change Handler

Description

protected UI\Controls\Spin::onChange()

Shall be executed when the value in this Spin changes

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • « UI\Controls\Spin::onChange
  • UI\Controls\Slider »
  • PHP Manual
  • UI\Controls\Spin
  • Set Value

UI\Controls\Spin::setValue

(UI 0.9.9)

UI\Controls\Spin::setValue — Set Value

Description

public UI\Controls\Spin::setValue(int $value)

Set the value in this Spin

Parameters

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Slider Control

(UI 0.9.9)

Introduction

A Slider is a control which represents a range, and a current value in the range. The sliding element of the control (sometimes called the "thumb") reflects the value, and can be adjusted within the range.

Class synopsis

class UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct(int $min, int $max)
/* Methods */
public getValue(): int
protected onChange()
public setValue(int $value)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Slider::__construct — Construct a new Slider
  • UI\Controls\Slider::getValue — Get Value
  • UI\Controls\Slider::onChange — Change Handler
  • UI\Controls\Slider::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Slider

  • « UI\Controls\Slider
  • UI\Controls\Slider::getValue »
  • PHP Manual
  • UI\Controls\Slider
  • Construct a new Slider

UI\Controls\Slider::__construct

(UI 0.9.9)

UI\Controls\Slider::__construct — Construct a new Slider

Description

public UI\Controls\Slider::__construct(int $min, int $max)

Construct a new Slider with the given range

Parameters

min

The minimum allowed value

max

The maximum allowed value

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • « UI\Controls\Slider::__construct
  • UI\Controls\Slider::onChange »
  • PHP Manual
  • UI\Controls\Slider
  • Get Value

UI\Controls\Slider::getValue

(UI 0.9.9)

UI\Controls\Slider::getValue — Get Value

Description

public UI\Controls\Slider::getValue(): int

Get the value from this Slider

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\Slider::getValue
  • UI\Controls\Slider::setValue »
  • PHP Manual
  • UI\Controls\Slider
  • Change Handler

UI\Controls\Slider::onChange

(UI 0.9.9)

UI\Controls\Slider::onChange — Change Handler

Description

protected UI\Controls\Slider::onChange()

Shall be executed when the value of this Slider changes

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • « UI\Controls\Slider::onChange
  • UI\Controls\Progress »
  • PHP Manual
  • UI\Controls\Slider
  • Set Value

UI\Controls\Slider::setValue

(UI 0.9.9)

UI\Controls\Slider::setValue — Set Value

Description

public UI\Controls\Slider::setValue(int $value)

Shall set the value for this Slider

Parameters

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Progress Control

(UI 0.9.9)

Introduction

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Class synopsis

class UI\Controls\Progress extends UI\Control {
/* Methods */
public getValue(): int
public setValue(int $value)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Progress::getValue — Get Value
  • UI\Controls\Progress::setValue — Set Value

User Contributed Notes

There are no user contributed notes for this page.


Get Value

  • « UI\Controls\Progress
  • UI\Controls\Progress::setValue »
  • PHP Manual
  • UI\Controls\Progress
  • Get Value

UI\Controls\Progress::getValue

(UI 0.9.9)

UI\Controls\Progress::getValue — Get Value

Description

public UI\Controls\Progress::getValue(): int

Shall retrieve the current value of this Progress bar

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Value

  • « UI\Controls\Progress::getValue
  • UI\Controls\Separator »
  • PHP Manual
  • UI\Controls\Progress
  • Set Value

UI\Controls\Progress::setValue

(UI 0.9.9)

UI\Controls\Progress::setValue — Set Value

Description

public UI\Controls\Progress::setValue(int $value)

Shall set the value for this Progress bar

Parameters

value

An integer between 0 and 100 (inclusive)

User Contributed Notes

There are no user contributed notes for this page.


Control Separator

(UI 0.9.9)

Introduction

A Separator represents a control separator, it has no other function.

Class synopsis

class UI\Controls\Separator extends UI\Control {
/* Constants */
const int Horizontal;
const int Vertical;
/* Constructor */
public __construct(int $type = UI\Controls\Separator::Horizontal)
/* Inherited methods */
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()
}

Predefined Constants

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Table of Contents

  • UI\Controls\Separator::__construct — Construct a new Separator

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Separator

  • « UI\Controls\Separator
  • UI\Controls\Combo »
  • PHP Manual
  • UI\Controls\Separator
  • Construct a new Separator

UI\Controls\Separator::__construct

(UI 0.9.9)

UI\Controls\Separator::__construct — Construct a new Separator

Description

public UI\Controls\Separator::__construct(int $type = UI\Controls\Separator::Horizontal)

Shall construct a new Separator of the given type

Parameters

type

Separator::Horizonal or Separator::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Combo Control

(UI 0.9.9)

Introduction

A Combo control represents a list of options, like the familiar select HTML element.

Class synopsis

class UI\Controls\Combo extends UI\Control {
/* Methods */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Combo::append — Append Option
  • UI\Controls\Combo::getSelected — Get Selected Option
  • UI\Controls\Combo::onSelected — Selected Handler
  • UI\Controls\Combo::setSelected — Set Selected Option

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • « UI\Controls\Combo
  • UI\Controls\Combo::getSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Append Option

UI\Controls\Combo::append

(UI 0.9.9)

UI\Controls\Combo::append — Append Option

Description

public UI\Controls\Combo::append(string $text)

Append an option to this Combo

Parameters

text

The text for the new option

User Contributed Notes

There are no user contributed notes for this page.


Get Selected Option

  • « UI\Controls\Combo::append
  • UI\Controls\Combo::onSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Get Selected Option

UI\Controls\Combo::getSelected

(UI 0.9.9)

UI\Controls\Combo::getSelected — Get Selected Option

Description

public UI\Controls\Combo::getSelected(): int

Shall retrieve the index of the option selected in this Combo

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Selected Handler

  • « UI\Controls\Combo::getSelected
  • UI\Controls\Combo::setSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Selected Handler

UI\Controls\Combo::onSelected

(UI 0.9.9)

UI\Controls\Combo::onSelected — Selected Handler

Description

protected UI\Controls\Combo::onSelected()

Shall be executed when an option is selected in this Combo

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Selected Option

  • « UI\Controls\Combo::onSelected
  • UI\Controls\EditableCombo »
  • PHP Manual
  • UI\Controls\Combo
  • Set Selected Option

UI\Controls\Combo::setSelected

(UI 0.9.9)

UI\Controls\Combo::setSelected — Set Selected Option

Description

public UI\Controls\Combo::setSelected(int $index)

Shall set the currently selected option in this Combo

Parameters

index

The index of the option to select

User Contributed Notes

There are no user contributed notes for this page.


EdiableCombo Control

(UI 0.9.9)

Introduction

An Editable Combo is a Combo which allows the user to enter custom options

Class synopsis

class UI\Controls\EditableCombo extends UI\Control {
/* Methods */
public append(string $text)
public getText(): string
protected onChange()
public setText(string $text)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\EditableCombo::append — Append Option
  • UI\Controls\EditableCombo::getText — Get Text
  • UI\Controls\EditableCombo::onChange — Change Handler
  • UI\Controls\EditableCombo::setText — Set Text

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • « UI\Controls\EditableCombo
  • UI\Controls\EditableCombo::getText »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Append Option

UI\Controls\EditableCombo::append

(UI 0.9.9)

UI\Controls\EditableCombo::append — Append Option

Description

public UI\Controls\EditableCombo::append(string $text)

Shall append a new option to this Editable Combo

Parameters

text

The text for the new option

User Contributed Notes

There are no user contributed notes for this page.


Get Text

  • « UI\Controls\EditableCombo::append
  • UI\Controls\EditableCombo::onChange »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Get Text

UI\Controls\EditableCombo::getText

(UI 0.9.9)

UI\Controls\EditableCombo::getText — Get Text

Description

public UI\Controls\EditableCombo::getText(): string

Get the value of the currently selected option in this Editable Combo

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Change Handler

  • « UI\Controls\EditableCombo::getText
  • UI\Controls\EditableCombo::setText »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Change Handler

UI\Controls\EditableCombo::onChange

(UI 0.9.9)

UI\Controls\EditableCombo::onChange — Change Handler

Description

protected UI\Controls\EditableCombo::onChange()

Shall be executed when the value of this Editable Combobox changes

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Text

  • « UI\Controls\EditableCombo::onChange
  • UI\Controls\Radio »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Set Text

UI\Controls\EditableCombo::setText

(UI 0.9.9)

UI\Controls\EditableCombo::setText — Set Text

Description

public UI\Controls\EditableCombo::setText(string $text)

Shall set the text of the currently selected option in this Editable Combo

Parameters

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Radio Control

(UI 0.9.9)

Introduction

A Radio is similar to the radio input type familiar from HTML

Class synopsis

class UI\Controls\Radio extends UI\Control {
/* Methods */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Inherited methods */
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()
}

Table of Contents

  • UI\Controls\Radio::append — Append Option
  • UI\Controls\Radio::getSelected — Get Selected Option
  • UI\Controls\Radio::onSelected — Selected Handler
  • UI\Controls\Radio::setSelected — Set Selected Option

User Contributed Notes

There are no user contributed notes for this page.


Append Option

  • « UI\Controls\Radio
  • UI\Controls\Radio::getSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Append Option

UI\Controls\Radio::append

(UI 0.9.9)

UI\Controls\Radio::append — Append Option

Description

public UI\Controls\Radio::append(string $text)

Shall append a new option to this Radio

Parameters

text

The text (label) for the option

User Contributed Notes

There are no user contributed notes for this page.


Get Selected Option

  • « UI\Controls\Radio::append
  • UI\Controls\Radio::onSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Get Selected Option

UI\Controls\Radio::getSelected

(UI 0.9.9)

UI\Controls\Radio::getSelected — Get Selected Option

Description

public UI\Controls\Radio::getSelected(): int

Shall retrieve the index of the currently selected option in this Radio

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Selected Handler

  • « UI\Controls\Radio::getSelected
  • UI\Controls\Radio::setSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Selected Handler

UI\Controls\Radio::onSelected

(UI 0.9.9)

UI\Controls\Radio::onSelected — Selected Handler

Description

protected UI\Controls\Radio::onSelected()

Shall be executed when the option selected in this Radio changes

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Selected Option

  • « UI\Controls\Radio::onSelected
  • UI\Controls\Picker »
  • PHP Manual
  • UI\Controls\Radio
  • Set Selected Option

UI\Controls\Radio::setSelected

(UI 0.9.9)

UI\Controls\Radio::setSelected — Set Selected Option

Description

public UI\Controls\Radio::setSelected(int $index)

Shall set the currently selected option in this Radio

Parameters

index

The index of the option to select

User Contributed Notes

There are no user contributed notes for this page.


Picker Control

(UI 0.9.9)

Introduction

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Class synopsis

class UI\Controls\Picker extends UI\Control {
/* Constants */
const int Date;
const int Time;
const int DateTime;
/* Constructor */
public __construct(int $type = UI\Controls\Picker::Date)
/* Inherited methods */
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()
}

Predefined Constants

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Table of Contents

  • UI\Controls\Picker::__construct — Construct a new Picker

User Contributed Notes

falcon560 at gmail dot com 05-Nov-2017 07:54
No getter method for the date/time


Construct a new Picker

  • « UI\Controls\Picker
  • UI\Controls\Form »
  • PHP Manual
  • UI\Controls\Picker
  • Construct a new Picker

UI\Controls\Picker::__construct

(UI 0.9.9)

UI\Controls\Picker::__construct — Construct a new Picker

Description

public UI\Controls\Picker::__construct(int $type = UI\Controls\Picker::Date)

Construct a new Picker of the given type

Parameters

type

Picker::Date, Picker::Time, or Picker::DateTime

User Contributed Notes

There are no user contributed notes for this page.


Control Form (Arrangement)

(UI 0.9.9)

Introduction

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Class synopsis

class UI\Controls\Form extends UI\Control {
/* Properties */
protected $controls;
/* Methods */
public append(string $label, UI\Control $control, bool $stretchy = false): int
public delete(int $index): bool
public isPadded(): bool
public setPadded(bool $padded)
/* Inherited methods */
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()
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Form::append — Append Control
  • UI\Controls\Form::delete — Delete Control
  • UI\Controls\Form::isPadded — Padding Detection
  • UI\Controls\Form::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • « UI\Controls\Form
  • UI\Controls\Form::delete »
  • PHP Manual
  • UI\Controls\Form
  • Append Control

UI\Controls\Form::append

(UI 0.9.9)

UI\Controls\Form::append — Append Control

Description

public UI\Controls\Form::append(string $label, UI\Control $control, bool $stretchy = false): int

Shall append the control to the form, and set the label

Parameters

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Return Values

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Delete Control

  • « UI\Controls\Form::append
  • UI\Controls\Form::isPadded »
  • PHP Manual
  • UI\Controls\Form
  • Delete Control

UI\Controls\Form::delete

(UI 0.9.9)

UI\Controls\Form::delete — Delete Control

Description

public UI\Controls\Form::delete(int $index): bool

Shall delete the control at the given index in this Form

Parameters

index

The index of the control to remove

Return Values

Indication of succcess

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • « UI\Controls\Form::delete
  • UI\Controls\Form::setPadded »
  • PHP Manual
  • UI\Controls\Form
  • Padding Detection

UI\Controls\Form::isPadded

(UI 0.9.9)

UI\Controls\Form::isPadded — Padding Detection

Description

public UI\Controls\Form::isPadded(): bool

Shall detect if padding is enabled on this Form

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • « UI\Controls\Form::isPadded
  • UI\Controls\Grid »
  • PHP Manual
  • UI\Controls\Form
  • Set Padding

UI\Controls\Form::setPadded

(UI 0.9.9)

UI\Controls\Form::setPadded — Set Padding

Description

public UI\Controls\Form::setPadded(bool $padded)

Shall enable or disable padding on this Form

Parameters

padded

User Contributed Notes

There are no user contributed notes for this page.


Control Grid (Arrangement)

(UI 0.9.9)

Introduction

A Grid is a control which is allows the arrangement of children into a grid

Class synopsis

class UI\Controls\Grid extends UI\Control {
/* Constants */
const int Fill;
const int Start;
const int Center;
const int End;
const int Leading;
const int Top;
const int Trailing;
const int Bottom;
/* Properties */
protected $controls;
/* Methods */
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)
/* Inherited methods */
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()
}

Predefined Constants

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

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Grid::append — Append Control
  • UI\Controls\Grid::isPadded — Padding Detection
  • UI\Controls\Grid::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • « UI\Controls\Grid
  • UI\Controls\Grid::isPadded »
  • PHP Manual
  • UI\Controls\Grid
  • Append Control

UI\Controls\Grid::append

(UI 0.9.9)

UI\Controls\Grid::append — Append Control

Description

public UI\Controls\Grid::append(
UI\Control $control,
int $left,
int $top,
int $xspan,
int $yspan,
bool $hexpand,
int $halign,
bool $vexpand,
int $valign
)

Warning

This function is currently not documented; only its argument list is available.

Parameters

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • « UI\Controls\Grid::append
  • UI\Controls\Grid::setPadded »
  • PHP Manual
  • UI\Controls\Grid
  • Padding Detection

UI\Controls\Grid::isPadded

(UI 0.9.9)

UI\Controls\Grid::isPadded — Padding Detection

Description

public UI\Controls\Grid::isPadded(): bool

Shall detect if padding is enabled on this Grid

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • « UI\Controls\Grid::isPadded
  • UI\Controls\Group »
  • PHP Manual
  • UI\Controls\Grid
  • Set Padding

UI\Controls\Grid::setPadded

(UI 0.9.9)

UI\Controls\Grid::setPadded — Set Padding

Description

public UI\Controls\Grid::setPadded(bool $padding)

Shall enable or disable padding for this Grid

Parameters

padding

User Contributed Notes

There are no user contributed notes for this page.


Control Group (Arrangement)

(UI 0.9.9)

Introduction

A Group is a titled container for child controls

Class synopsis

class UI\Controls\Group extends UI\Control {
/* Properties */
protected $controls;
/* Constructor */
public __construct(string $title)
/* Methods */
public append(UI\Control $control)
public getTitle(): string
public hasMargin(): bool
public setMargin(bool $margin)
public setTitle(string $title)
/* Inherited methods */
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()
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Group::append — Append Control
  • UI\Controls\Group::__construct — Construct a new Group
  • UI\Controls\Group::getTitle — Get Title
  • UI\Controls\Group::hasMargin — Margin Detection
  • UI\Controls\Group::setMargin — Set Margin
  • UI\Controls\Group::setTitle — Set Title

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • « UI\Controls\Group
  • UI\Controls\Group::__construct »
  • PHP Manual
  • UI\Controls\Group
  • Append Control

UI\Controls\Group::append

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

UI\Controls\Group::append — Append Control

Description

public UI\Controls\Group::append(UI\Control $control)

Shall append a control to this Group

Parameters

control

The control to append

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Group

  • « UI\Controls\Group::append
  • UI\Controls\Group::getTitle »
  • PHP Manual
  • UI\Controls\Group
  • Construct a new Group

UI\Controls\Group::__construct

(UI 0.9.9)

UI\Controls\Group::__construct — Construct a new Group

Description

public UI\Controls\Group::__construct(string $title)

Shall construct a new Group with the given title

Parameters

title

The text for the title label

User Contributed Notes

There are no user contributed notes for this page.


Get Title

  • « UI\Controls\Group::__construct
  • UI\Controls\Group::hasMargin »
  • PHP Manual
  • UI\Controls\Group
  • Get Title

UI\Controls\Group::getTitle

(UI 0.9.9)

UI\Controls\Group::getTitle — Get Title

Description

public UI\Controls\Group::getTitle(): string

Shall return the current title for this Group

Parameters

This function has no parameters.

Return Values

The current title

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • « UI\Controls\Group::getTitle
  • UI\Controls\Group::setMargin »
  • PHP Manual
  • UI\Controls\Group
  • Margin Detection

UI\Controls\Group::hasMargin

(UI 0.9.9)

UI\Controls\Group::hasMargin — Margin Detection

Description

public UI\Controls\Group::hasMargin(): bool

Shall detect if this Group has a margin

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Margin

  • « UI\Controls\Group::hasMargin
  • UI\Controls\Group::setTitle »
  • PHP Manual
  • UI\Controls\Group
  • Set Margin

UI\Controls\Group::setMargin

(UI 0.9.9)

UI\Controls\Group::setMargin — Set Margin

Description

public UI\Controls\Group::setMargin(bool $margin)

Shall enable or disable margins for this Group

Parameters

margin

User Contributed Notes

There are no user contributed notes for this page.


Set Title

  • « UI\Controls\Group::setMargin
  • UI\Controls\Box »
  • PHP Manual
  • UI\Controls\Group
  • Set Title

UI\Controls\Group::setTitle

(UI 0.9.9)

UI\Controls\Group::setTitle — Set Title

Description

public UI\Controls\Group::setTitle(string $title)

Shall set the title for this Group

Parameters

title

The text for the new title

User Contributed Notes

There are no user contributed notes for this page.


Control Box (Arrangement)

(UI 0.9.9)

Introduction

A Box allows the arrangement of other controls

Class synopsis

class UI\Controls\Box extends UI\Control {
/* Constants */
const int Vertical;
const int Horizontal;
/* Properties */
protected $controls;
/* Constructor */
public __construct(int $orientation = UI\Controls\Box::Horizontal)
/* Methods */
public append(Control $control, bool $stretchy = false): int
public delete(int $index): bool
public getOrientation(): int
public isPadded(): bool
public setPadded(bool $padded)
/* Inherited methods */
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()
}

Properties

controls

Contains controls, should not be manipulated directly

Predefined Constants

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Table of Contents

  • UI\Controls\Box::append — Append Control
  • UI\Controls\Box::__construct — Construct a new Box
  • UI\Controls\Box::delete — Delete Control
  • UI\Controls\Box::getOrientation — Get Orientation
  • UI\Controls\Box::isPadded — Padding Detection
  • UI\Controls\Box::setPadded — Set Padding

User Contributed Notes

There are no user contributed notes for this page.


Append Control

  • « UI\Controls\Box
  • UI\Controls\Box::__construct »
  • PHP Manual
  • UI\Controls\Box
  • Append Control

UI\Controls\Box::append

(UI 0.9.9)

UI\Controls\Box::append — Append Control

Description

public UI\Controls\Box::append(Control $control, bool $stretchy = false): int

Shall append the given control to this Box

Parameters

control

The control to append

stretchy

Set true to stretch the control

Return Values

Shall return the index of the appended control, may be 0

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Box

  • « UI\Controls\Box::append
  • UI\Controls\Box::delete »
  • PHP Manual
  • UI\Controls\Box
  • Construct a new Box

UI\Controls\Box::__construct

(UI 0.9.9)

UI\Controls\Box::__construct — Construct a new Box

Description

public UI\Controls\Box::__construct(int $orientation = UI\Controls\Box::Horizontal)

Shall construct a new box

Parameters

orientation

Box::Horizontal or Box::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Delete Control

  • « UI\Controls\Box::__construct
  • UI\Controls\Box::getOrientation »
  • PHP Manual
  • UI\Controls\Box
  • Delete Control

UI\Controls\Box::delete

(UI 0.9.9)

UI\Controls\Box::delete — Delete Control

Description

public UI\Controls\Box::delete(int $index): bool

Shall delete the control at the given index from this Box

Parameters

index

The index of the control to delete

Return Values

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Get Orientation

  • « UI\Controls\Box::delete
  • UI\Controls\Box::isPadded »
  • PHP Manual
  • UI\Controls\Box
  • Get Orientation

UI\Controls\Box::getOrientation

(UI 0.9.9)

UI\Controls\Box::getOrientation — Get Orientation

Description

public UI\Controls\Box::getOrientation(): int

Shall retrieve the orientation of this Box

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Padding Detection

  • « UI\Controls\Box::getOrientation
  • UI\Controls\Box::setPadded »
  • PHP Manual
  • UI\Controls\Box
  • Padding Detection

UI\Controls\Box::isPadded

(UI 0.9.9)

UI\Controls\Box::isPadded — Padding Detection

Description

public UI\Controls\Box::isPadded(): bool

Shall detect if padding is enabled on this Box

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Set Padding

  • « UI\Controls\Box::isPadded
  • UI\Draw\Pen »
  • PHP Manual
  • UI\Controls\Box
  • Set Padding

UI\Controls\Box::setPadded

(UI 0.9.9)

UI\Controls\Box::setPadded — Set Padding

Description

public UI\Controls\Box::setPadded(bool $padded)

Shall enable or disable padding on this Box

Parameters

padded

User Contributed Notes

There are no user contributed notes for this page.


Draw Pen

(UI 0.9.9)

Introduction

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Class synopsis

final class UI\Draw\Pen {
/* Methods */
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)
}

Table of Contents

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Fill a Path
  • UI\Draw\Pen::restore — Restore
  • UI\Draw\Pen::save — Save
  • UI\Draw\Pen::stroke — Stroke a Path
  • UI\Draw\Pen::transform — Matrix Transform
  • UI\Draw\Pen::write — Draw Text at Point

User Contributed Notes

There are no user contributed notes for this page.


Clip a Path

  • « UI\Draw\Pen
  • UI\Draw\Pen::fill »
  • PHP Manual
  • UI\Draw\Pen
  • Clip a Path

UI\Draw\Pen::clip

(UI 0.9.9)

UI\Draw\Pen::clip — Clip a Path

Description

public UI\Draw\Pen::clip(UI\Draw\Path $path)

Shall clip the given Path

Parameters

path

The path to clip

User Contributed Notes

There are no user contributed notes for this page.


Fill a Path

  • « UI\Draw\Pen::clip
  • UI\Draw\Pen::restore »
  • PHP Manual
  • UI\Draw\Pen
  • Fill a Path

UI\Draw\Pen::fill

(UI 0.9.9)

UI\Draw\Pen::fill — Fill a Path

Description

public UI\Draw\Pen::fill(UI\Draw\Path $path, UI\Draw\Brush $with)
public UI\Draw\Pen::fill(UI\Draw\Path $path, UI\Draw\Color $with)
public UI\Draw\Pen::fill(UI\Draw\Path $path, int $with)

Shall fill the given path

Parameters

path

The path to fill

with

The color or brush to fill with

User Contributed Notes

There are no user contributed notes for this page.


Restore

  • « UI\Draw\Pen::fill
  • UI\Draw\Pen::save »
  • PHP Manual
  • UI\Draw\Pen
  • Restore

UI\Draw\Pen::restore

(UI 0.9.9)

UI\Draw\Pen::restore — Restore

Description

public UI\Draw\Pen::restore()

Shall restore a previously saved Pen

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Save

  • « UI\Draw\Pen::restore
  • UI\Draw\Pen::stroke »
  • PHP Manual
  • UI\Draw\Pen
  • Save

UI\Draw\Pen::save

(UI 0.9.9)

UI\Draw\Pen::save — Save

Description

public UI\Draw\Pen::save()

Shall save the Pen

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Stroke a Path

  • « UI\Draw\Pen::save
  • UI\Draw\Pen::transform »
  • PHP Manual
  • UI\Draw\Pen
  • Stroke a Path

UI\Draw\Pen::stroke

(UI 0.9.9)

UI\Draw\Pen::stroke — Stroke a Path

Description

public UI\Draw\Pen::stroke(UI\Draw\Path $path, UI\Draw\Brush $with, UI\Draw\Stroke $stroke)
public UI\Draw\Pen::stroke(UI\Draw\Path $path, UI\Draw\Color $with, UI\Draw\Stroke $stroke)
public UI\Draw\Pen::stroke(UI\Draw\Path $path, int $with, UI\Draw\Stroke $stroke)

Shall stroke the given path

Parameters

path

The path to stroke

with

The color or brush to stroke with

stroke

The configuration of the stroke

User Contributed Notes

There are no user contributed notes for this page.


Matrix Transform

  • « UI\Draw\Pen::stroke
  • UI\Draw\Pen::write »
  • PHP Manual
  • UI\Draw\Pen
  • Matrix Transform

UI\Draw\Pen::transform

(UI 0.9.9)

UI\Draw\Pen::transform — Matrix Transform

Description

public UI\Draw\Pen::transform(UI\Draw\Matrix $matrix)

Shall perform matrix transformation

Parameters

matrix

The matrix to use

User Contributed Notes

There are no user contributed notes for this page.


Draw Text at Point

  • « UI\Draw\Pen::transform
  • UI\Draw\Path »
  • PHP Manual
  • UI\Draw\Pen
  • Draw Text at Point

UI\Draw\Pen::write

(UI 0.9.9)

UI\Draw\Pen::write — Draw Text at Point

Description

public UI\Draw\Pen::write(UI\Point $point, UI\Draw\Text\Layout $layout)

Shall draw the given text layout at the given point

Parameters

point

The point to perform the drawing

layout

The layout of the text to draw

User Contributed Notes

There are no user contributed notes for this page.


Draw Path

(UI 0.9.9)

Introduction

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Class synopsis

class UI\Draw\Path {
/* Constants */
const int Winding;
const int Alternate;
/* Constructor */
public __construct(int $mode = UI\Draw\Path::Winding)
/* Methods */
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
)
}

Predefined Constants

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Table of Contents

  • UI\Draw\Path::addRectangle — Draw a Rectangle
  • UI\Draw\Path::arcTo — Draw an Arc
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Close Figure
  • UI\Draw\Path::__construct — Construct a new Path
  • UI\Draw\Path::end — Finalize Path
  • UI\Draw\Path::lineTo — Draw a Line
  • UI\Draw\Path::newFigure — Draw Figure
  • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

User Contributed Notes

There are no user contributed notes for this page.


Draw a Rectangle

  • « UI\Draw\Path
  • UI\Draw\Path::arcTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Rectangle

UI\Draw\Path::addRectangle

(UI 0.9.9)

UI\Draw\Path::addRectangle — Draw a Rectangle

Description

public UI\Draw\Path::addRectangle(UI\Point $point, UI\Size $size)

Shall map the path of a rectangle of the given size, at the given point

Parameters

point

The point to begin the shape

size

The size of the rectangle

User Contributed Notes

There are no user contributed notes for this page.


Draw an Arc

  • « UI\Draw\Path::addRectangle
  • UI\Draw\Path::bezierTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw an Arc

UI\Draw\Path::arcTo

(UI 0.9.9)

UI\Draw\Path::arcTo — Draw an Arc

Description

public UI\Draw\Path::arcTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for an arc

Parameters

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

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Draw Bezier Curve

  • « UI\Draw\Path::arcTo
  • UI\Draw\Path::closeFigure »
  • PHP Manual
  • UI\Draw\Path
  • Draw Bezier Curve

UI\Draw\Path::bezierTo

(UI 0.9.9)

UI\Draw\Path::bezierTo — Draw Bezier Curve

Description

public UI\Draw\Path::bezierTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall draw a bezier curve

Parameters

point

The point at which to begin mapping

radius

The radius of the curve

angle

The angle of the curve

sweep

The sweep of the curve

negative

User Contributed Notes

There are no user contributed notes for this page.


Close Figure

  • « UI\Draw\Path::bezierTo
  • UI\Draw\Path::__construct »
  • PHP Manual
  • UI\Draw\Path
  • Close Figure

UI\Draw\Path::closeFigure

(UI 0.9.9)

UI\Draw\Path::closeFigure — Close Figure

Description

public UI\Draw\Path::closeFigure()

Shall close the current figure

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Path

  • « UI\Draw\Path::closeFigure
  • UI\Draw\Path::end »
  • PHP Manual
  • UI\Draw\Path
  • Construct a new Path

UI\Draw\Path::__construct

(UI 0.9.9)

UI\Draw\Path::__construct — Construct a new Path

Description

public UI\Draw\Path::__construct(int $mode = UI\Draw\Path::Winding)

Shall construct a new path in the given mode

Parameters

mode

Path::Winding or Path::Alternate

User Contributed Notes

There are no user contributed notes for this page.


Finalize Path

  • « UI\Draw\Path::__construct
  • UI\Draw\Path::lineTo »
  • PHP Manual
  • UI\Draw\Path
  • Finalize Path

UI\Draw\Path::end

(UI 0.9.9)

UI\Draw\Path::end — Finalize Path

Description

public UI\Draw\Path::end()

Shall finalize this Path

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Draw a Line

  • « UI\Draw\Path::end
  • UI\Draw\Path::newFigure »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Line

UI\Draw\Path::lineTo

(UI 0.9.9)

UI\Draw\Path::lineTo — Draw a Line

Description

public UI\Draw\Path::lineTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for a line

Parameters

point

The point to begin mapping

radius

angle

sweep

negative

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure

  • « UI\Draw\Path::lineTo
  • UI\Draw\Path::newFigureWithArc »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure

UI\Draw\Path::newFigure

(UI 0.9.9)

UI\Draw\Path::newFigure — Draw Figure

Description

public UI\Draw\Path::newFigure(UI\Point $point)

Shall map a new figure at the given point

Parameters

point

The point to begin mapping

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure with Arc

  • « UI\Draw\Path::newFigure
  • UI\Draw\Matrix »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure with Arc

UI\Draw\Path::newFigureWithArc

(UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

Description

public UI\Draw\Path::newFigureWithArc(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Parameters

point

radius

angle

sweep

negative

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

Introduction

Class synopsis

class UI\Draw\Matrix {
/* Methods */
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)
}

Table of Contents

  • UI\Draw\Matrix::invert — Invert Matrix
  • UI\Draw\Matrix::isInvertible — Invertible Detection
  • UI\Draw\Matrix::multiply — Multiply Matrix
  • UI\Draw\Matrix::rotate — Rotate Matrix
  • UI\Draw\Matrix::scale — Scale Matrix
  • UI\Draw\Matrix::skew — Skew Matrix
  • UI\Draw\Matrix::translate — Translate Matrix

User Contributed Notes

There are no user contributed notes for this page.


Invert Matrix

  • « UI\Draw\Matrix
  • UI\Draw\Matrix::isInvertible »
  • PHP Manual
  • UI\Draw\Matrix
  • Invert Matrix

UI\Draw\Matrix::invert

(UI 0.9.9)

UI\Draw\Matrix::invert — Invert Matrix

Description

public UI\Draw\Matrix::invert()

Shall invert this matrix

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Invertible Detection

  • « UI\Draw\Matrix::invert
  • UI\Draw\Matrix::multiply »
  • PHP Manual
  • UI\Draw\Matrix
  • Invertible Detection

UI\Draw\Matrix::isInvertible

(UI 0.9.9)

UI\Draw\Matrix::isInvertible — Invertible Detection

Description

public UI\Draw\Matrix::isInvertible(): bool

Shall detect if this Matrix may be inverted

Parameters

This function has no parameters.

User Contributed Notes

There are no user contributed notes for this page.


Multiply Matrix

  • « UI\Draw\Matrix::isInvertible
  • UI\Draw\Matrix::rotate »
  • PHP Manual
  • UI\Draw\Matrix
  • Multiply Matrix

UI\Draw\Matrix::multiply

(UI 0.9.9)

UI\Draw\Matrix::multiply — Multiply Matrix

Description

public UI\Draw\Matrix::multiply(UI\Draw\Matrix $matrix): UI\Draw\Matrix

Shall multiply this matrix with the given matrix

Parameters

This function has no parameters.

Return Values

The new Matrix

User Contributed Notes

There are no user contributed notes for this page.


Rotate Matrix

  • « UI\Draw\Matrix::multiply
  • UI\Draw\Matrix::scale »
  • PHP Manual
  • UI\Draw\Matrix
  • Rotate Matrix

UI\Draw\Matrix::rotate

(UI 0.9.9)

UI\Draw\Matrix::rotate — Rotate Matrix

Description

public UI\Draw\Matrix::rotate(UI\Point $point, float $amount)

Shall rotate this Matrix

Parameters

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Scale Matrix

  • « UI\Draw\Matrix::rotate
  • UI\Draw\Matrix::skew »
  • PHP Manual
  • UI\Draw\Matrix
  • Scale Matrix

UI\Draw\Matrix::scale

(UI 0.9.9)

UI\Draw\Matrix::scale — Scale Matrix

Description

public UI\Draw\Matrix::scale(UI\Point $center, UI\Point $point)

Shall scale this Matrix

Parameters

center

point

User Contributed Notes

There are no user contributed notes for this page.


Skew Matrix

  • « UI\Draw\Matrix::scale
  • UI\Draw\Matrix::translate »
  • PHP Manual
  • UI\Draw\Matrix
  • Skew Matrix

UI\Draw\Matrix::skew

(UI 0.9.9)

UI\Draw\Matrix::skew — Skew Matrix

Description

public UI\Draw\Matrix::skew(UI\Point $point, UI\Point $amount)

Shall skew this Matrix

Parameters

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Translate Matrix

  • « UI\Draw\Matrix::skew
  • UI\Draw\Color »
  • PHP Manual
  • UI\Draw\Matrix
  • Translate Matrix

UI\Draw\Matrix::translate

(UI 0.9.9)

UI\Draw\Matrix::translate — Translate Matrix

Description

public UI\Draw\Matrix::translate(UI\Point $point)

Shall translate this Matrix

Parameters

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

Introduction

Represents RGBA colours, individual channels are accessible via public properties.

Class synopsis

class UI\Draw\Color {
/* Constants */
const int Red;
const int Green;
const int Blue;
const int Alpha;
/* Properties */
public $r;
public $g;
public $b;
public $a;
/* Constructor */
public __construct(UI\Draw\Color $color = ?)
public __construct(int $color = ?)
/* Methods */
public getChannel(int $channel): float
public setChannel(int $channel, float $value): void
}

Properties

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

Predefined Constants

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

Table of Contents

  • UI\Draw\Color::__construct — Construct new Color
  • UI\Draw\Color::getChannel — Color Manipulation
  • UI\Draw\Color::setChannel — Color Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Construct new Color

  • « UI\Draw\Color
  • UI\Draw\Color::getChannel »
  • PHP Manual
  • UI\Draw\Color
  • Construct new Color

UI\Draw\Color::__construct

(UI 0.9.9)

UI\Draw\Color::__construct — Construct new Color

Description

public UI\Draw\Color::__construct(UI\Draw\Color $color = ?)
public UI\Draw\Color::__construct(int $color = ?)

Shall construct a new color

Parameters

color

May be UI\Draw\Color or RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • « UI\Draw\Color::__construct
  • UI\Draw\Color::setChannel »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::getChannel

(UI 0.9.9)

UI\Draw\Color::getChannel — Color Manipulation

Description

public UI\Draw\Color::getChannel(int $channel): float

Shall retrieve the value for a channel

Parameters

channel

Constant channel identity

Return Values

The current value of the requested channel

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • « UI\Draw\Color::getChannel
  • UI\Draw\Stroke »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::setChannel

(UI 0.9.9)

UI\Draw\Color::setChannel — Color Manipulation

Description

public UI\Draw\Color::setChannel(int $channel, float $value): void

Shall set the selected channel to the given value

Parameters

channel

Constant channel identity

value

The new value for the selected channel

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

Introduction

Holds the configuration for the Pen to perform a stroke

Class synopsis

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
)
/* Methods */
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)
}

Table of Contents

  • UI\Draw\Stroke::__construct — Construct a new Stroke
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Get Line Join
  • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
  • UI\Draw\Stroke::getThickness — Get Thickness
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Set Line Join
  • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
  • UI\Draw\Stroke::setThickness — Set Thickness

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Stroke

  • « UI\Draw\Stroke
  • UI\Draw\Stroke::getCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Construct a new Stroke

UI\Draw\Stroke::__construct

(UI 0.9.9)

UI\Draw\Stroke::__construct — Construct a new Stroke

Description

public UI\Draw\Stroke::__construct(
int $cap = UI\Draw\Line\Cap::Flat,
int $join = UI\Draw\Line\Join::Miter,
float $thickness = 1,
float $miterLimit = 10
)

Shall construct a new Stroke

Parameters

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

thickness

The thickness of the stroke

miterLimit

Miter limit (default is sensible for all supported platforms)

User Contributed Notes

There are no user contributed notes for this page.


Get Line Cap

  • « UI\Draw\Stroke::__construct
  • UI\Draw\Stroke::getJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Cap

UI\Draw\Stroke::getCap

(UI 0.9.9)

UI\Draw\Stroke::getCap — Get Line Cap

Description

public UI\Draw\Stroke::getCap(): int

Shall retrieve the line cap setting of this Stroke

Parameters

This function has no parameters.

Return Values

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Get Line Join

  • « UI\Draw\Stroke::getCap
  • UI\Draw\Stroke::getMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Join

UI\Draw\Stroke::getJoin

(UI 0.9.9)

UI\Draw\Stroke::getJoin — Get Line Join

Description

public UI\Draw\Stroke::getJoin(): int

Shall retrieve the line join setting of this Stroke

Parameters

This function has no parameters.

Return Values

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

User Contributed Notes

There are no user contributed notes for this page.


Get Miter Limit

  • « UI\Draw\Stroke::getJoin
  • UI\Draw\Stroke::getThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Miter Limit

UI\Draw\Stroke::getMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Get Miter Limit

Description

public UI\Draw\Stroke::getMiterLimit(): float

Shall retrieve the miter limit of this Stroke

Parameters

This function has no parameters.

Return Values

The current miter limit

User Contributed Notes

There are no user contributed notes for this page.


Get Thickness

  • « UI\Draw\Stroke::getMiterLimit
  • UI\Draw\Stroke::setCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Thickness

UI\Draw\Stroke::getThickness

(UI 0.9.9)

UI\Draw\Stroke::getThickness — Get Thickness

Description

public UI\Draw\Stroke::getThickness(): float

Shall retrieve the thickness of this Stroke

Parameters

This function has no parameters.

Return Values

The current thickness

User Contributed Notes

There are no user contributed notes for this page.


Set Line Cap

  • « UI\Draw\Stroke::getThickness
  • UI\Draw\Stroke::setJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Cap

UI\Draw\Stroke::setCap

(UI 0.9.9)

UI\Draw\Stroke::setCap — Set Line Cap

Description

public UI\Draw\Stroke::setCap(int $cap)

Shall set the line cap setting for this Stroke

Parameters

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Set Line Join

  • « UI\Draw\Stroke::setCap
  • UI\Draw\Stroke::setMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Join

UI\Draw\Stroke::setJoin

(UI 0.9.9)

UI\Draw\Stroke::setJoin — Set Line Join

Description

public UI\Draw\Stroke::setJoin(int $join)

Shall set the line join setting for this Stroke

Parameters

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Set Miter Limit

  • « UI\Draw\Stroke::setJoin
  • UI\Draw\Stroke::setThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Miter Limit

UI\Draw\Stroke::setMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Set Miter Limit

Description

public UI\Draw\Stroke::setMiterLimit(float $limit)

Set the miter limit for this Stroke

Parameters

limit

The new limit

User Contributed Notes

There are no user contributed notes for this page.


Set Thickness

  • « UI\Draw\Stroke::setMiterLimit
  • UI\Draw\Brush »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Thickness

UI\Draw\Stroke::setThickness

(UI 0.9.9)

UI\Draw\Stroke::setThickness — Set Thickness

Description

public UI\Draw\Stroke::setThickness(float $thickness)

Shall set the thickness for this Stroke

Parameters

thickness

The new thickness

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

Introduction

Represents a solid color brush

Class synopsis

class UI\Draw\Brush {
/* Constructor */
public __construct(UI\Draw\Color $color)
public __construct(int $color)
/* Methods */
public getColor(): UI\Draw\Color
public setColor(UI\Draw\Color $color): void
public setColor(int $color): void
}

Table of Contents

  • UI\Draw\Brush::__construct — Construct a new Brush
  • UI\Draw\Brush::getColor — Get Color
  • UI\Draw\Brush::setColor — Set Color

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Brush

  • « UI\Draw\Brush
  • UI\Draw\Brush::getColor »
  • PHP Manual
  • UI\Draw\Brush
  • Construct a new Brush

UI\Draw\Brush::__construct

(UI 0.9.9)

UI\Draw\Brush::__construct — Construct a new Brush

Description

public UI\Draw\Brush::__construct(UI\Draw\Color $color)
public UI\Draw\Brush::__construct(int $color)

Shall construct a solid brush using the given color

Parameters

color

Can be a UI\Draw\Color or RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Get Color

  • « UI\Draw\Brush::__construct
  • UI\Draw\Brush::setColor »
  • PHP Manual
  • UI\Draw\Brush
  • Get Color

UI\Draw\Brush::getColor

(UI 0.9.9)

UI\Draw\Brush::getColor — Get Color

Description

public UI\Draw\Brush::getColor(): UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Parameters

This function has no parameters.

Return Values

The current color of the brush

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • « UI\Draw\Brush::getColor
  • UI\Draw\Brush\Gradient »
  • PHP Manual
  • UI\Draw\Brush
  • Set Color

UI\Draw\Brush::setColor

(UI 0.9.9)

UI\Draw\Brush::setColor — Set Color

Description

public UI\Draw\Brush::setColor(UI\Draw\Color $color): void
public UI\Draw\Brush::setColor(int $color): void

Shall set the color of this brush to the color provided

Parameters

color

Can be a UI\Draw\Color or RRGGBBAA

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

Introduction

Abstract for gradient brushes

Class synopsis

abstract class UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Methods */
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
/* Inherited methods */
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
}

Table of Contents

  • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::setStop — Stop Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • « UI\Draw\Brush\Gradient
  • UI\Draw\Brush\Gradient::delStop »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::addStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::addStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::addStop(float $position, UI\Draw\Color $color): int
public UI\Draw\Brush\Gradient::addStop(float $position, int $color): int

Shall at a stop of the given color at the given position

Parameters

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Return Values

Total number of stops

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • « UI\Draw\Brush\Gradient::addStop
  • UI\Draw\Brush\Gradient::setStop »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::delStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::delStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::delStop(int $index): int

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Return Values

Total number of stops

User Contributed Notes

There are no user contributed notes for this page.


Stop Manipulation

  • « UI\Draw\Brush\Gradient::delStop
  • UI\Draw\Brush\LinearGradient »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::setStop

(UI 2.0.0)

UI\Draw\Brush\Gradient::setStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::setStop(int $index, float $position, UI\Draw\Color $color): bool
public UI\Draw\Brush\Gradient::setStop(int $index, float $position, int $color): bool

Parameters

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

Return Values

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

Introduction

Class synopsis

class UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $end)
/* Inherited methods */
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
}

Table of Contents

  • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

User Contributed Notes

There are no user contributed notes for this page.


Construct a Linear Gradient

  • « UI\Draw\Brush\LinearGradient
  • UI\Draw\Brush\RadialGradient »
  • PHP Manual
  • UI\Draw\Brush\LinearGradient
  • Construct a Linear Gradient

UI\Draw\Brush\LinearGradient::__construct

(UI 2.0.0)

UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

Description

public UI\Draw\Brush\LinearGradient::__construct(UI\Point $start, UI\Point $end)

Shall construct a new linear gradient

Parameters

start

end

User Contributed Notes

There are no user contributed notes for this page.


Radial Gradient

(UI 2.0.0)

Introduction

Class synopsis

class UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $outer, float $radius)
/* Inherited methods */
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
}

Table of Contents

  • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Radial Gradient

  • « UI\Draw\Brush\RadialGradient
  • UI\Draw\Text\Layout »
  • PHP Manual
  • UI\Draw\Brush\RadialGradient
  • Construct a new Radial Gradient

UI\Draw\Brush\RadialGradient::__construct

(UI 2.0.0)

UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

Description

public UI\Draw\Brush\RadialGradient::__construct(UI\Point $start, UI\Point $outer, float $radius)

Shall construct a new radial gradient

Parameters

start

outer

radius

User Contributed Notes

There are no user contributed notes for this page.


Represents Text Layout

(UI 0.9.9)

Introduction

A Text Layout represents the layout of text which will be drawn by the Pen

Class synopsis

class UI\Draw\Text\Layout {
/* Constructor */
public __construct(string $text, UI\Draw\Text\Font $font, float $width)
/* Methods */
public setColor(UI\Draw\Color $color, int $start = 0, int $end = ?)
public setColor(int $color, int $start = 0, int $end = ?)
public setWidth(float $width)
}

Table of Contents

  • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
  • UI\Draw\Text\Layout::setColor — Set Color
  • UI\Draw\Text\Layout::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Text Layout

  • « UI\Draw\Text\Layout
  • UI\Draw\Text\Layout::setColor »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Construct a new Text Layout

UI\Draw\Text\Layout::__construct

(UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construct a new Text Layout

Description

public UI\Draw\Text\Layout::__construct(string $text, UI\Draw\Text\Font $font, float $width)

Shall construct a new Text Layout

Parameters

text

The text for the layout

font

The font to use for writing

width

The width of the layout

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • « UI\Draw\Text\Layout::__construct
  • UI\Draw\Text\Layout::setWidth »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Color

UI\Draw\Text\Layout::setColor

(UI 0.9.9)

UI\Draw\Text\Layout::setColor — Set Color

Description

public UI\Draw\Text\Layout::setColor(UI\Draw\Color $color, int $start = 0, int $end = ?)
public UI\Draw\Text\Layout::setColor(int $color, int $start = 0, int $end = ?)

Shall set the Color for all of, or a range of the text in the Layout

Parameters

color

The color to use

start

The starting character

end

The ending character, by default the end of the string

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • « UI\Draw\Text\Layout::setColor
  • UI\Draw\Text\Font »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Width

UI\Draw\Text\Layout::setWidth

(UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Set Width

Description

public UI\Draw\Text\Layout::setWidth(float $width)

Shall set the width of this Text Layout

Parameters

width

The new width

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

Introduction

Loads a described font

Class synopsis

class UI\Draw\Text\Font {
/* Constructor */
public __construct(UI\Draw\Text\Font\Descriptor $descriptor)
/* Methods */
public getAscent(): float
public getDescent(): float
public getLeading(): float
public getUnderlinePosition(): float
public getUnderlineThickness(): float
}

Table of Contents

  • UI\Draw\Text\Font::__construct — Construct a new Font
  • UI\Draw\Text\Font::getAscent — Font Metrics
  • UI\Draw\Text\Font::getDescent — Font Metrics
  • UI\Draw\Text\Font::getLeading — Font Metrics
  • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
  • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Font

  • « UI\Draw\Text\Font
  • UI\Draw\Text\Font::getAscent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Construct a new Font

UI\Draw\Text\Font::__construct

(UI 0.9.9)

UI\Draw\Text\Font::__construct — Construct a new Font

Description

public UI\Draw\Text\Font::__construct(UI\Draw\Text\Font\Descriptor $descriptor)

Shall construct a new Font using the given descriptor

Parameters

descriptor

The descriptor for the Font

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::__construct
  • UI\Draw\Text\Font::getDescent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getAscent

(UI 1.0.3)

UI\Draw\Text\Font::getAscent — Font Metrics

Description

public UI\Draw\Text\Font::getAscent(): float

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getAscent
  • UI\Draw\Text\Font::getLeading »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getDescent

(UI 1.0.3)

UI\Draw\Text\Font::getDescent — Font Metrics

Description

public UI\Draw\Text\Font::getDescent(): float

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getDescent
  • UI\Draw\Text\Font::getUnderlinePosition »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getLeading

(UI 1.0.3)

UI\Draw\Text\Font::getLeading — Font Metrics

Description

public UI\Draw\Text\Font::getLeading(): float

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getLeading
  • UI\Draw\Text\Font::getUnderlineThickness »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlinePosition

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Font Metrics

Description

public UI\Draw\Text\Font::getUnderlinePosition(): float

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getUnderlinePosition
  • UI\Draw\Text\Font\Descriptor »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlineThickness

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

Description

public UI\Draw\Text\Font::getUnderlineThickness(): float

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

Introduction

Describes a font

Class synopsis

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
)
/* Methods */
public getFamily(): string
public getItalic(): int
public getSize(): float
public getStretch(): int
public getWeight(): int
}

Table of Contents

  • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
  • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
  • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
  • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
  • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Font Descriptor

  • « UI\Draw\Text\Font\Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Construct a new Font Descriptor

UI\Draw\Text\Font\Descriptor::__construct

(UI 0.9.9)

UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor

Description

public UI\Draw\Text\Font\Descriptor::__construct(
string $family,
float $size,
int $weight = UI\Draw\Text\Font\Weight::Normal,
int $italic = UI\Draw\Text\Font\Italic::Normal,
int $stretch = UI\Draw\Text\Font\Stretch::Normal
)

Shall construct a new Font Descriptor

Parameters

family

The name of a valid family of fonts

size

The preferred size

weight

UI\Draw\Text\Font\Weight constant

italic

UI\Draw\Text\Font\Italic constant

stretch

UI\Draw\Text\Font\Stretch constant

User Contributed Notes

There are no user contributed notes for this page.


Get Font Family

  • « UI\Draw\Text\Font\Descriptor::__construct
  • UI\Draw\Text\Font\Descriptor::getItalic »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Get Font Family

UI\Draw\Text\Font\Descriptor::getFamily

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family

Description

public UI\Draw\Text\Font\Descriptor::getFamily(): string

Shall return the requested font family

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Style Detection

  • « UI\Draw\Text\Font\Descriptor::getFamily
  • UI\Draw\Text\Font\Descriptor::getSize »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getItalic

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getItalic — Style Detection

Description

public UI\Draw\Text\Font\Descriptor::getItalic(): int

Shall return constant setting

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Size Detection

  • « UI\Draw\Text\Font\Descriptor::getItalic
  • UI\Draw\Text\Font\Descriptor::getStretch »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Size Detection

UI\Draw\Text\Font\Descriptor::getSize

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getSize — Size Detection

Description

public UI\Draw\Text\Font\Descriptor::getSize(): float

Shall return the requested size

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Style Detection

  • « UI\Draw\Text\Font\Descriptor::getSize
  • UI\Draw\Text\Font\Descriptor::getWeight »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getStretch

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getStretch — Style Detection

Description

public UI\Draw\Text\Font\Descriptor::getStretch(): int

Shall return requested stretch

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Functions »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Weight Detection

UI\Draw\Text\Font\Descriptor::getWeight

(UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

Description

public UI\Draw\Text\Font\Descriptor::getWeight(): int

Shall return requested weight

Parameters

This function has no parameters.

Return Values

User Contributed Notes

There are no user contributed notes for this page.


UI Functions

Table of Contents

  • 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 Functions
  • UI\quit »
  • PHP Manual
  • UI Functions
  • Retrieve Font Families

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

Description

UI\Draw\Text\Font\fontFamilies(): array

Returns an array of valid font families for the current system

Parameters

This function has no parameters.

Return Values

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 Functions
  • Quit UI Loop

UI\quit

(UI 2.0.0)

UI\quit — Quit UI Loop

Description

UI\quit(): void

Shall cause the main loop to be exited

Parameters

This function has no parameters.

Return Values

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 Functions
  • Enter UI Loop

UI\run

(UI 2.0.0)

UI\run — Enter UI Loop

Description

UI\run(int $flags = ?): void

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

Parameters

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

Return Values

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

Introduction

Class synopsis

final class UI\Draw\Text\Font\Weight {
/* Constants */
const int Thin;
const int UltraLight;
const int Light;
const int Book;
const int Normal;
const int Medium;
const int SemiBold;
const int Bold;
const int UltraBold;
const int Heavy;
const int UltraHeavy;
}

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

Introduction

Class synopsis

final class UI\Draw\Text\Font\Italic {
/* Constants */
const int Normal = 0;
const int Oblique = 1;
const int Italic = 2;
}

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

Introduction

Class synopsis

final class UI\Draw\Text\Font\Stretch {
/* Constants */
const int UltraCondensed = 0;
const int ExtraCondensed = 1;
const int Condensed = 2;
const int SemiCondensed = 3;
const int Normal = 4;
const int SemiExpanded = 5;
const int Expanded = 6;
const int ExtraExpanded = 7;
const int UltraExpanded = 8;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

Introduction

Class synopsis

final class UI\Draw\Line\Cap {
/* Constants */
const int Flat;
const int Round;
const int Square;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

Introduction

Class synopsis

final class UI\Draw\Line\Join {
/* Constants */
const int Miter;
const int Round;
const int Bevel;
}

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

Introduction

Class synopsis

final class UI\Key {
/* Constants */
const int Escape;
const int Insert;
const int Delete;
const int Home;
const int End;
const int PageUp;
const int PageDown;
const int Up;
const int Down;
const int Left;
const int Right;
const int F1;
const int F2;
const int F3;
const int F4;
const int F5;
const int F6;
const int F7;
const int F8;
const int F9;
const int F10;
const int F11;
const int F12;
const int N0;
const int N1;
const int N2;
const int N3;
const int N4;
const int N5;
const int N6;
const int N7;
const int N8;
const int N9;
const int NDot;
const int NEnter;
const int NAdd;
const int NSubtract;
const int NMultiply;
const int NDivide;
}

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

Introduction

Class synopsis

class UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


RuntimeException

(UI 1.0.3)

Introduction

Class synopsis

class UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Inherited properties */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Inherited methods */
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

  • General Information
  • Mailing lists
  • Obtaining PHP
  • Database issues
  • Installation
  • Build Problems
  • Using PHP
  • Password Hashing — Safe Password Hashing
  • PHP and HTML
  • PHP and COM
  • Miscellaneous Questions

User Contributed Notes

There are no user contributed notes for this page.


General Information

This section holds the most general questions about PHP: what it is and what it does.

  1. What is PHP?
  2. What does PHP stand for?
  3. What is the relation between the versions?
  4. Can I run several versions of PHP at the same time?
  5. I think I found a bug! Who should I tell?
What is PHP?

From the preface of the manual:

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

What does PHP stand for?

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. For more information, the curious can visit » Free On-Line Dictionary of Computing or the » Wikipedia entry on recursive acronyms.

What is the relation between the versions?

PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 8 is the current generation of PHP, which uses the Zend engine 4 which, among other things, offers many additional OOP features.

Can I run several versions of PHP at the same time?

Yes. See the INSTALL file that is included in the PHP source distribution.

I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at » https://github.com/php/php-src/issues.

User Contributed Notes

There are no user contributed notes for this page.


Mailing lists

This section holds questions about how to get in touch with the PHP community. The best way is the mailing lists.

  1. Are there any PHP mailing lists?
  2. Are there any other communities?
  3. Can I start my own PHP mailing list?
  4. Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!
  5. Is there an archive of the mailing lists anywhere?
  6. What can I ask the mailing list?
  7. What information should I include when posting to the mailing list?
Are there any PHP mailing lists?

Of course! There are many mailing lists for several subjects. The most common community mailing lists can be found on our » mailing list page.

The most general mailing list is php-general. To subscribe, send a blank email message to » php-general-subscribe@lists.php.net. To unsubscribe, send a blank email to » php-general-unsubscribe@lists.php.net.

You can also subscribe and unsubscribe using the web interface on our » mailing list page, and unsubscribe instructions are included in the footer of every mailing list message.

Are there any other communities?

There are countless PHP-centric communities around the world, and we have links to some of these resources (and information on how to learn more) on our » Support page.

Can I start my own PHP mailing list?

Absolutely! In fact, we not only freely allow it, we encourage it! Helping others by sharing your knowledge and experience with PHP helps to foster the growth and development of the global PHP community and the language itself.

Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!

If you have problems subscribing to or unsubscribing from a mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address is joeblow@example.com, and you are trying to subscribe to php-general, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.

The most common reason folks have a hard time unsubscribing from our mailing lists is due to the use of mail forwarders. For example, if your email address is danbrown@example.com, but you subscribed to the mailing list with the forwarder php-lists@example.com and forward that to danbrown@example.com, attempting to unsubscribe danbrown@example.com will not work, as that address is not even known to our systems. Instead, you will need to unsubscribe the address to which the mail is being sent - in this example, php-lists@example.com.

Is there an archive of the mailing lists anywhere?

Yes, you will find links to some of the archive sites on the » mailing list page. You will also find dozens of sites that archive and/or syndicate our mailing list content by using your favorite Internet search engine and searching for "php mailing list archives".

All mailing list articles are also archived as news messages. You can access the news server at » news://news.php.net/ with a news client. There is also an experimental web interface for the news server at » http://news.php.net/

What can I ask the mailing list?

Since PHP is growing more and more popular by the day, the traffic on the php-general mailing list can be very heavy, ranging from 75 to 200 or more posts per day. Because of this, it is in everyone's interest that you use the list as a last resort, when you have exhausted all other avenues.

Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP, please read through all included documentation and README's. If you still can't find any information that helps you out, you're more than welcome to use the appropriate mailing list.

To ensure that you receive the best responses (and to reduce the likelihood of frustrating your fellow developers), please be sure to post your question to the appropriate list. For example, if you are having difficulties installing PHP, you should send your question to the php-install mailing list. A caveat: some lists have similar names and completely different uses; a question regarding PHP scripts on Windows should be directed to the Windows PHP users list, not to the Windows Internals list.

Before asking questions, you may want to read the paper on » How To Ask Questions The Smart Way as this is a good idea for everyone.

What information should I include when posting to the mailing list?

Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include the operating system being used, the version of PHP you're trying to use, how you got it (pre-compiled, Git, RPM, and so on), what you have done so far, and the exact error message or present result.

This goes for any other problem as well: you must include an explanation of what you have done, what you're trying to do, and any error messages encountered in the process. If you're having problems with your source code, you should include the part of the code that isn't working, indicating which line is the problem by an appropriately-placed code comment. Do not include more code than necessary though! It makes the post difficult to read, causing many to ignore your request. If you're unsure about how much information should be included, post what you believe is immediately relevant to your present issue, and be prepared to provide more information upon request.

Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.

And lastly, you're encouraged to read the paper on » How To Ask Questions The Smart Way as this will be a great help for everyone, especially yourself.

User Contributed Notes

There are no user contributed notes for this page.


Obtaining PHP

This section has details about PHP download locations, and OS issues.

  1. Where can I obtain PHP?
  2. Are pre-compiled binary versions available?
  3. Where can I get libraries needed to compile some of the optional PHP extensions?
  4. How do I get these libraries to work?
  5. I got the latest version of the PHP source code from the Git repository on my Windows machine, what do I need to compile it?
  6. Where do I find the Browser Capabilities File?
  7. What does thread safety mean when downloading PHP?
Where can I obtain PHP?

You can download PHP from any of the members of the PHP network of sites. These can be found at » https://www.php.net/. You can also use anonymous Git to get the absolute latest version of the source. For more information, go to » https://www.php.net/git.php.

Are pre-compiled binary versions available?

We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our » Downloads page, for Linux binaries, please visit your distribution's website.

Where can I get libraries needed to compile some of the optional PHP extensions?

Note: Those marked with a * are to the best of our knowledge not thread safe; they are not recommended for use in a multi-threaded environment.

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

How do I get these libraries to work?

You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.

I got the latest version of the PHP source code from the Git repository on my Windows machine, what do I need to compile it?

See the PHP Wiki for the latest instructions: » Step by Step Build Instructions

Where do I find the Browser Capabilities File?

You can find a browscap.ini file at » http://browscap.org/.

What does thread safety mean when downloading PHP?

Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.

So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.

User Contributed Notes

There are no user contributed notes for this page.


Database issues

This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.

  1. I heard it's possible to access Microsoft SQL Server from PHP. How?
  2. Can I access Microsoft Access databases?
I heard it's possible to access Microsoft SQL Server from PHP. How?

On Unix machines you can use PDO_ODBC or the Unified ODBC API.

On Windows machines you can also use PDO_SQLSRV or SQLSRV.

Also see the answer to the next question.

Can I access Microsoft Access databases?

If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. » OpenLink Software has Unix-based ODBC drivers that can do this.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our » website for a free download.

One option that has proved successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

  • Install MySQL on your platform according to instructions with MySQL. Latest available from » http://www.mysql.com/ No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
  • Download the MyODBC for Windows driver from the MySQL site. Install it on your Windows machine. You can test the operation with the utilities included with this program.
  • Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
  • Install Access with a full install, this makes sure you get the proper add-ins... at the least you will need ODBC support and the linked table manager.
  • Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks:

  • You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.
  • When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access
  • If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.

User Contributed Notes

doug at unlikelysource dot com 31-Mar-2017 08:53
To enable SQL Server access from ubuntu 16.04:

* Run these commands:
```
sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > mssql-release.list
sudo mv mssql-release.list /etc/apt/sources.list.d
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql unixodbc-dev
sudo apt-get install php7.1-dev
sudo apt-get install autoconf
sudo pecl install pdo_sqlsrv-4.1.6.1
```

*  Confirm ODBC driver installation:
```
odbcinst -q -d -n "ODBC Driver 13 for SQL Server"
```

* Update the php.ini file: run` php --ini` to find the path to your php.ini file
* Add this line to /path/to/php.ini
```
extension=pdo_sqlsrv.so
```
* Run `php -i` to confirm SQLSRV support was added
* NOTE: extensions (on my computer) were installed here:
`/usr/local/lib/php/extensions/no-debug-non-zts-20160303/`

* Test user access directly on the Windows server running MSSQL:
```
sqlcmd -S ip_address -U username -P password -d database -q "select * from table_name"
```
* On the Windows server: open port 1433 in your firewall

* Install the FreeTds utils to test the connection:
```
sudo apt-get install freetds-bin
tsql -H mssql.host.ip.address -U username -P password -D database -p 1433
```

* Formulate the correct DSN (Data Source Name):
    See: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php

* Sample PHP Code:
```
<?php
// Database params
$tcp  = '192.168.3.126';
$port = 1433;
$user = "test";
$password = "Password123";
$database = "test";

// Open connection
try {
    // Database connect -- use one of the two statements below
    $dsn =  'sqlsrv:Server=tcp:' . $tcp . ',' . $port . ';Database=' . $database;
    $dbh = new PDO( $dsn, $user, $password, array());
    // SQL prepare
    $sql = "SELECT * FROM prospects";
    $sth = $dbh->prepare($sql);
    // Execute
    $sth->execute();
    // Fetch results
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $output = '<pre>';
        $output .= implode("\t", array_keys($row)) . PHP_EOL;
        $output .= implode("\t", $row) . PHP_EOL;
        while ($row = $sth->fetch(PDO::FETCH_NUM)) {
            $output .= implode("\t", $row) . PHP_EOL;
        }
    }
} catch (PDOException $e) {
    $output .= $e->getMessage();
}
$output .= '</pre>';
echo $output;
```
knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.


Installation

This section holds common questions about the way to install PHP. PHP is available for almost any OS, and almost any web server.

To install PHP, follow the instructions in Installation and Configuration.

  1. Why shouldn't I use Apache2 with a threaded MPM in a production environment?
  2. Unix/Windows: Where should my php.ini file be located?
  3. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
  4. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
  5. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
  6. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
  7. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
  8. Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!
  11. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..
  12. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.
  13. How do I add my PHP directory to the PATH on Windows?
  14. How do I make the php.ini file available to PHP on windows?
  15. Is it possible to use Apache content negotiation (MultiViews option) with PHP?
  16. Is PHP limited to process GET and POST request methods only?
Why shouldn't I use Apache2 with a threaded MPM in a production environment?

PHP is glue. It is the glue used to build cool web applications by sticking dozens of 3rd-party libraries together and making it all appear as one coherent entity through an intuitive and easy to learn language interface. The flexibility and power of PHP relies on the stability and robustness of the underlying platform. It needs a working OS, a working web server and working 3rd-party libraries to glue together. When any of these stop working PHP needs ways to identify the problems and fix them quickly. When you make the underlying framework more complex by not having completely separate execution threads, completely separate memory segments and a strong sandbox for each request to play in, further weaknesses are introduced into PHP's system.

If you want to use a threaded MPM, look at a FastCGI configuration where PHP is running in its own memory space.

Unix/Windows: Where should my php.ini file be located?

By default on Unix it should be in /usr/local/lib which is <install-path>/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:

--with-config-file-path=/etc
And then you would copy php.ini-development from the distribution to /etc/php.ini and edit it to make any local changes you want.

--with-config-file-scan-dir=PATH

On Windows the default path for the php.ini file is the Windows directory. If you're using the Apache webserver, php.ini is first searched in the Apaches install directory, e.g. c:\program files\apache group\apache. This way you can have different php.ini files for different versions of Apache on the same machine.

See also the chapter about the configuration file.

Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?

This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:

  • Stop your httpd processes

  • gdb httpd

  • Stop your httpd processes

  • > run -X -f /path/to/httpd.conf

  • Then fetch the URL causing the problem with your browser

  • > run -X -f /path/to/httpd.conf

  • If you are getting a core dump, gdb should inform you of this now

  • type: bt

  • You should include your backtrace in your bug report. This should be submitted to » https://github.com/php/php-src/issues

If your script uses the regular expression functions (preg_match() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x

Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?

Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your httpd.conf file:

# 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
And add:
AddType application/x-httpd-php .php
... to the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.

Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.

Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.

Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.

Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.

Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors:
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib, others do not. This is also covered in the MySQL FAQ.

Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working.

Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:

  • File permissions on your PHP script, php.exe, php5ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.
  • The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.
Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine. Also, you will want to read this faq.

When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..

You must set the cgi.force_redirect directive to 0. It defaults to 1 so be sure the directive isn't commented out (with a ;). Like all directives, this is set in php.ini

Because the default is 1, it's critical that you're 100% sure that the correct php.ini file is being read. Read this faq for details.

How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.

To be sure your php.ini is being read by PHP, make a call to phpinfo(). Near the top, there will be a listing called Configuration File (php.ini). This will tell you where PHP is looking for php.ini and whether or not it's being read. If just a directory PATH exists, then it's not being read, and you should put your php.ini in that directory. If php.ini is included within the PATH, it is being read.

If php.ini is being read and you're running PHP as a module, then be sure to restart your web server after making changes to php.ini

See also php_ini_loaded_file().

How do I add my PHP directory to the PATH on Windows?

On Windows:

  • Go to Control Panel and open the System icon (Start → Control Panel)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System Variables' pane

  • Find the Path entry (you may need to scroll to find it)

  • Double click on the Path entry

  • Enter your PHP directory at the end, including ';' before (e.g. ;C:\php)

  • Press OK

Note: Be sure to reboot after following the steps above to ensure that the PATH changes are applied.

How do I make the php.ini file available to PHP on windows?

There are several ways of doing this. If you are using Apache, refer to the Apache documentation, otherwise you must set the PHPRC environment variable.

Is it possible to use Apache content negotiation (MultiViews option) with PHP?

If links to PHP files include extension, everything works perfect. This FAQ is only for the case when links to PHP files don't include extension and you want to use content negotiation to choose PHP files from URL with no extension. In this case, replace the line AddType application/x-httpd-php .php with:

AddHandler php5-script php
AddType text/html php
This solution doesn't work for Apache 1 as PHP module doesn't catch php-script.

Is PHP limited to process GET and POST request methods only?

No, it is possible to handle any request method, e.g. CONNECT. Proper response status can be sent with header(). If only GET and POST methods should be handled, it can be achieved with this Apache configuration:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

User Contributed Notes

ssaxena at nriol dot com 12-Mar-2010 02:28
Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:\Program Files\PHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:\PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:\PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4
john dot calder at manukau dot ac dot nz 03-May-2008 10:19
WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components".
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths.
I have found no need to configure IIS.
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo();
?>

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.
charleslynch at xybersoftware dot com 17-Apr-2008 07:30
One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...
joerg at fenin dot de 02-Nov-2007 02:35
To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly..

http://www.askapache.com/online-tools/request-method-scanner/
scott at chaisson dot net 19-Sep-2007 09:18
Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:\winnt\php.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:\winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:\WWW\PHP\ext
  doc_root = C:\WWW\Site
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>\php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>\php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase
christianfelix at laszlo dot com 16-Jul-2007 03:39
For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini,

You have to follow the suggestions, add to path, uncomment extensions and voila!!
Meiki67 skipthis at geemail 07-Jun-2007 04:41
Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:\drive_d) and installed PHP in D:\PHP - which in reality is C:\DRIVE_D\PHP.  To make a long story short - only after (1) changing all substituted D:\ back to C:\DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki
Curtis 18-May-2007 07:39
I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log
knutw at sparhell dot no 06-Nov-2006 09:15
I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:\Program Files\PHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'æt know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.
13-Sep-2006 07:03
After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:\php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:\php\php.ini," all of a sudden I was getting honest to goodness PHP pages working.
emzeperx at emzeper dot hu 01-Jan-2006 12:36
You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:\php

command to extend immediately the path var.
JUSTANOTHERUSER 14-Aug-2005 11:23
<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start
per dot fikse at ipj dot no 12-Jul-2005 01:22
Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 ,
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)
barry dot fagin at usafa dot af dot mil 04-Jan-2005 09:22
Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files.

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:\php\php-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF
jeff_graham at datacenterservices dot net 01-Feb-2004 01:51
As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)
nigel dot salt at hotmail dot com 13-Dec-2003 05:00
Finally got IIS 5 and PHP 5 to talk.

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
W3SVC\Parameters\Script Map]
".php"="your path to php\\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
 set application name to the name of the folder
 set executable and script as permission
 set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel
jimo at mail dot azhsv dot com 29-Nov-2003 07:33
PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition ? Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:\windows\system32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:\php\php.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:\php\php.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile ? the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won?t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)
peter dot mosinskisNOSPAM at csuci dot edu 06-Mar-2003 12:36
Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method.

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the \WINNT\system32\inetsrv\urlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com
monroe at peoplego dot com 17-May-2002 10:32
INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support.
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added
--with-mysql=/usr/local   and it worked.

Good Luck


Build Problems

This section gathers most common errors that occur at build time.

  1. I got the latest version of PHP using the anonymous Git service, but there's no configure script!
  2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
  3. While configuring PHP (./configure), you come across an error similar to the following: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. When I try to start Apache, I get the following message: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
  6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
  7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
  8. When linking PHP, it complains about a number of undefined references.
  9. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.
  10. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
  11. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
  12. When I try to build PHP using --with-apxs I get strange error messages.
  13. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.
  14. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: 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', what's wrong?
  15. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
  16. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.
  17. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.
I got the latest version of PHP using the anonymous Git service, but there's no configure script!

You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the Git server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)

I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!

You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify --with-apache=/path/to/apache and not --with-apache=/path/to/apache/src.

While configuring PHP (./configure), you come across an error similar to the following:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.

When I try to start Apache, I get the following message:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:

--enable-shared=max --enable-rule=SHARED_CORE

For more information, read the top-level Apache INSTALL file or the Apache » DSO manual page.

When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!

You can make the configure script look for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.

You need to update your version of Bison. You can find the latest version at » http://www.gnu.org/software/bison/bison.html.

When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.

Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running cp *.o functions and then re-running make to see if that helps. If it does, you should really upgrade to a recent version of GNU make.

When linking PHP, it complains about a number of undefined references.

Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.

Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.

I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.

This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:

  • Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.
  • Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php .php Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
  • Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.

It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?

Note that the libphp4.a file is not supposed to exist. The apache process will create it!

When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.

This is a misleading error message from Apache that has been fixed in more recent versions.

When I try to build PHP using --with-apxs I get strange error messages.

There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command which apxs), it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
If this is what you see, you have found your problem. They may contain just spaces or other incorrect values, such as 'q()'. Change these lines to say:
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
The second possible problem should only be an issue on Red Hat 6.1 and 6.2. The apxs script Red Hat ships is broken. Look for this line:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
If you see the above line, change it to this:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Last, if you reconfigure/reinstall Apache, add a make clean to the process after ./configure and before make.

During make, I get errors in microtime, and a lot of RUSAGE_ stuff.

During the make portion of installation, if you encounter problems that look similar to this:

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

Your system is broken. You need to fix your /usr/include files by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
If that spews out errors, you know your include files are messed up.

When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: 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', what's wrong?

First, it's important to realize that this is a Warning and not a fatal error. Because this is often the last output seen during make, it may seem like a fatal error but it's not. Of course, if you set your compiler to die on Warnings, it will. Also keep in mind that MySQL support is enabled by default.

Note:

As of PHP 4.3.2, you'll also see the following text after the build (make) completes:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?

Either you look at config.nice file, in the source tree of your current PHP installation or, if this is not available, you simply run a

<?php phpinfo(); ?>
script. On top of the output the ./configure line, that was used to build this PHP installation is shown.

When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

Make sure your GD library and PHP are linked against the same depending libraries (e.g. libpng).

When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

Using non-GNU utilities while compiling PHP may cause problems. Be sure to use GNU tools in order to be certain that compiling PHP will work. For example, on Solaris, using either the SunOS BSD-compatible or Solaris versions of sed will not work, but using the GNU or Sun POSIX (xpg4) versions of sed will work. Links: » GNU sed, » GNU flex, and » GNU bison.

User Contributed Notes

Fabio 22-Feb-2012 01:47
When building PHP 5.3.x for Apache 2.4.x you may get an error in the apxs query for the MPM_NAME.
This is because the apxs included in Apache 2.4.x doesn't recognize that query anymore.

To resolve this issue one should modify the PHP configure file to use the right MPM module used by Apache.

To know the used MPM you can execute this command: apachectl -t -D DUMP_MODULES | grep mpm

Then, edit the PHP configure file, search for the APXS_MPM variable and force its value to prefork, event or worker according to the value returned by the previous command.

Hope it helps.
-
Fabio
terry at mackintoshweb dot com 19-Sep-2009 08:43
The configure script of PHP 5.3.0 has some test lines that use expr with the option --, my expr (version 2.0) does not except --.  This causes a run of error messages from the shell like:

./configure: line 2xxx: test: =: unary operator expected
expr: syntax error

I used buildconf --force to see if it would fix this.
While it resulted in a quit different file, it still had the lines of code with expr -- in it.
05-May-2007 06:48
@ anca-phpdoc at anca dot tv:

You can use ./configure --with-libxml-dir=/path_to_xml2-config
anca-phpdoc at anca dot tv 08-Dec-2005 07:48
For the configure newbies among us:

If you update or reinstall any of the libraries used to compile in a different directory than they started out, you will need to make sure that you update the config.cache file (or re-generate it) so that configure will not look in the wrong place for the information.

On Mac OS X, for example, I updated my libxml using Fink.  Fink placed the files in the /sw directory.  However, php was still looking for important libxml files (such as xml2-config) in the old directory (/usr/bin/xml2-config).   After updating config.cache with the new value of the xml2-config path, I was able to compile correctly.


Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

  1. I cannot remember the parameter order of PHP functions, are they random?
  2. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
  3. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
  4. When I do the following, the output is printed in the wrong order: <?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> what's going on?
  5. Hey, what happened to my newlines? <pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre>
  6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
  7. I need to access information in the request header directly. How can I do this?
  8. When I try to use authentication with IIS I get 'No Input file specified'.
  9. Windows: I can't access files shared on another computer using IIS
  10. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
  11. Where can I find a complete list of variables are available to me in PHP?
  12. How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.
  13. A few PHP directives may also take on shorthand byte values, as opposed to only int byte values. What are all the available shorthand byte options?
I cannot remember the parameter order of PHP functions, are they random?

PHP is a glue that brings together hundreds of external libraries, so sometimes this gets messy. However, a simple rule of thumb is as follows:

Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".

I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.

<?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 "None of the POSTed values are empty, posted:\n";
var_dump($post);
} else {
print "We have " . count($empty) . " empty values\n";
print "Posted:\n"; var_dump($post);
print "Empty:\n"; var_dump($empty);
exit;
}
?>

I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.

Assuming this is for a database, use the escaping mechanism that comes with the database. For example, use mysql_real_escape_string() with MySQL and pg_escape_string() with PostgreSQL. There is also the generic addslashes() and stripslashes() functions, that are more common with older PHP code.

When I do the following, the output is printed in the wrong order:
<?php
function myfunc($argument)
{
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo it.

Hey, what happened to my newlines?
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.

I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
echo "headers[$name] = $content<br />\n";
}
?>

See also
apache_lookup_uri(),
apache_response_headers(), and
fsockopen()

When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. This should not affect other NT web servers. For more information, see: » http://support.microsoft.com/kb/q160422/ and the manual section on HTTP Authentication .

Windows: I can't access files shared on another computer using IIS

You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.

You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.

How am I supposed to mix XML and PHP? It complains about my <?xml tags!

In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is On.

Where can I find a complete list of variables are available to me in PHP?

Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.

How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.

There are a few alternatives written in PHP such as » FPDF and » TCPDF.

A few PHP directives may also take on shorthand byte values, as opposed to only int byte values. What are all the available shorthand byte options?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes), and are all case-insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. These shorthand notations may be used in php.ini and in the ini_set() function. Note that the numeric value is cast to int; for instance, 0.5M is interpreted as 0.

Note: kilobyte versus kibibyte

The PHP notation describes one kilobyte as equalling 1024 bytes, whereas the IEC standard considers this to be a kibibyte instead. Summary: k and 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.


Safe Password Hashing

This section explains the reasons behind using hashing functions to secure passwords, as well as how to do so effectively.

  1. Why should I hash passwords supplied by users of my application?
  2. Why are common hashing functions such as md5 and sha1 unsuitable for passwords?
  3. How should I hash my passwords, if the common hash functions are not suitable?
  4. What is a salt?
  5. How do I store my salts?
Why should I hash passwords supplied by users of my application?

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application's database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

By applying a hashing algorithm to your user's passwords before storing them in your database, you make it implausible for any attacker to determine the original password, while still being able to compare the resulting hash to the original password in the future.

It is important to note, however, that hashing passwords only protects them from being compromised in your data store, but does not necessarily protect them from being intercepted by malicious code injected into your application itself.

Why are common hashing functions such as md5() and sha1() unsuitable for passwords?

Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to "brute force" the output of these algorithms, in order to determine the original input.

Because of how quickly a modern computer can "reverse" these hashing algorithms, many security professionals strongly suggest against their use for password hashing.

How should I hash my passwords, if the common hash functions are not suitable?

When hashing passwords, the two most important considerations are the computational expense, and the salt. The more computationally expensive the hashing algorithm, the longer it will take to brute force its output.

PHP provides a native password hashing API that safely handles both hashing and verifying passwords in a secure manner.

Another option is the crypt() function, which supports several hashing algorithms. When using this function, you are guaranteed that the algorithm you select is available, as PHP contains native implementations of each supported algorithm, in case one or more are not supported by your system.

The suggested algorithm to use when hashing passwords is Blowfish, which is also the default used by the password hashing API, as it is significantly more computationally expensive than MD5 or SHA1, while still being scalable.

Note that if you are using crypt() to verify a password, you will need to take care to prevent timing attacks by using a constant time string comparison. Neither PHP's == and === operators nor strcmp() perform constant time string comparisons. As password_verify() will do this for you, you are strongly encouraged to use the native password hashing API whenever possible.

What is a salt?

A cryptographic salt is data which is applied during the hashing process in order to eliminate the possibility of the output being looked up in a list of pre-calculated pairs of hashes and their input, known as a rainbow table.

In more simple terms, a salt is a bit of additional data which makes your hashes significantly more difficult to crack. There are a number of services online which provide extensive lists of pre-computed hashes, as well as the original input for those hashes. The use of a salt makes it implausible or impossible to find the resulting hash in one of these lists.

password_hash() will create a random salt if one isn't provided, and this is generally the easiest and most secure approach.

How do I store my salts?

When using password_hash() or crypt(), the return value includes the salt as part of the generated hash. This value should be stored verbatim in your database, as it includes information about the hash function that was used and can then be given directly to password_verify() or crypt() when verifying passwords.

The following diagram shows the format of a return value from crypt() or password_hash(). As you can see, they are self-contained, with all the information on the algorithm and salt required for future password verification.

The components of the value returned by password_hash and crypt: in order, the chosen algorithm, the algorithm's options, the salt used, and the hashed password.

User Contributed Notes

tamas at microwizard dot com 22-Sep-2021 08:23
While I am reading the comments some old math lessons came into my mind and started thinking. Using constants in a mathematical algorythms do not change the complexity of the algorythm itself.

The reason of salting is to avoid using rainbow tables (sorry guys this is the only reason) because it speeds up (shortcuts) the "actual" processing power.
(((Longer stored hashes AND longer password increases complexity of cracking NOT adding salt ALONE.)))

PHP salting functions returns all the needed information for checking passwords, therfore this information should be treated as constant from farther point of view. It is also a target for rainbow tables (sure: for much-much larger ones).

What is the solution?
The solution is to store password hash and salt on different places.
The implementation is yours. Every two different places will be good enough.

Yes, it will make problems for hackers. He/she needs to understand your system. No speed up for password cracking will work for him/her without reimplementing your whole system.

This is my two cent.
swardx at gmail dot com 29-Jun-2016 09:36
A great read..

https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/

Serious Security: How to store your users’ passwords safely

In summary, here is our minimum recommendation for safe storage of your users’ passwords:

    Use a strong random number generator to create a salt of 16 bytes or longer.
    Feed the salt and the password into the PBKDF2 algorithm.
    Use HMAC-SHA-256 as the core hash inside PBKDF2.
    Perform 20,000 iterations or more. (June 2016.)
    Take 32 bytes (256 bits) of output from PBKDF2 as the final password hash.
    Store the iteration count, the salt and the final hash in your password database.
    Increase your iteration count regularly to keep up with faster cracking tools.

Whatever you do, don’t try to knit your own password storage algorithm.
alf dot henrik at ascdevel dot com 12-Mar-2014 07:58
I feel like I should comment some of the clams being posted as replies here.

For starters, speed IS an issue with MD5 in particular and also SHA1. I've written my own MD5 bruteforce application just for the fun of it, and using only my CPU I can easily check a hash against about 200mill. hash per second. The main reason for this speed is that you for most attempts can bypass 19 out of 64 steps in the algorithm. For longer input (> 16 characters) it won't apply, but I'm sure there's some ways around it.

If you search online you'll see people claiming to be able to check against billions of hashes per second using GPUs. I wouldn't be surprised if it's possible to reach 100 billion per second on a single computer alone these days, and it's only going to get worse. It would require a watt monster with 4 dual high-end GPUs or something, but still possible.

Here's why 100 billion per second is an issue:
Assume most passwords contain a selection of 96 characters. A password with 8 characters would then have 96^8 = 7,21389578984e+15 combinations.
With 100 billion per second it would then take 7,21389578984e+15 / 3600 = ~20 hours to figure out what it actually says. Keep in mind that you'll need to add the numbers for 1-7 characters as well. 20 hours is not a lot if you want to target a single user.

So on essence:
There's a reason why newer hash algorithms are specifically designed not to be easily implemented on GPUs.

Oh, and I can see there's someone mentioning MD5 and rainbow tables. If you read the numbers here, I hope you realize how incredibly stupid and useless rainbow tables have become in terms of MD5. Unless the input to MD5 is really huge, you're just not going to be able to compete with GPUs here. By the time a storage media is able to produce far beyond 3TB/s, the CPUs and GPUs will have reached much higher speeds.

As for SHA1, my belief is that it's about a third slower than MD5. I can't verify this myself, but it seems to be the case judging the numbers presented for MD5 and SHA1. The issue with speeds is basically very much the same here as well.

The moral here:
Please do as told. Don't every use MD5 and SHA1 for hasing passwords ever again. We all know passwords aren't going to be that long for most people, and that's a major disadvantage. Adding long salts will help for sure, but unless you want to add some hundred bytes of salt, there's going to be fast bruteforce applications out there ready to reverse engineer your passwords or your users' passwords.
fluffy at beesbuzz dot biz 11-Jun-2012 11:33
The security issue with simple hashing (md5 et al) isn't really the speed, so much as the fact that it's idempotent; two different people with the same password will have the same hash, and so if one person's hash is brute-forced, the other one will as well.  This facilitates rainbow attacks.  Simply slowing the hash down isn't a very useful tactic for improving security.  It doesn't matter how slow and cumbersome your hash algorithm is - as soon as someone has a weak password that's in a dictionary, EVERYONE with that weak password is vulnerable.

Also, hash algorithms such as md5 are for the purpose of generating a digest and checking if two things are probably the same as each other; they are not intended to be impossible to generate a collision for.  Even if an underlying password itself requires a lot of brute forcing to determine, that doesn't mean it will be impossible to find some other bit pattern that generates the same hash in a trivial amount of time.

As such: please, please, PLEASE only use salted hashes for password storage.  There is no reason to implement your own salted hash mechanism, either, as crypt() already does an excellent job of this.


PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from external sources. The manual page on this topic includes many examples as well.

  1. What encoding/decoding do I need when I pass a value through a form/URL?
  2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
  3. How do I create arrays in a HTML <form>?
  4. How do I get all the results from a select multiple HTML tag?
  5. How can I pass a variable from Javascript to PHP?
What encoding/decoding do I need when I pass a value through a form/URL?

There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:

  • HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.

  • URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().

Example #1 A hidden HTML form element

<?php
echo '<input type="hidden" value="' . htmlspecialchars($data) . '" />'."\n";
?>

Note: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.

Example #2 Data to be edited by the user

<?php
echo "<textarea name='mydata'>\n";
echo htmlspecialchars($data)."\n";
echo "</textarea>";
?>

Note: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols. Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.

Example #3 In a URL

<?php
echo '<a href="' . htmlspecialchars("/nextpage.php?stage=23&data=" .
urlencode($data)) . '">'."\n";
?>

Note: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Note: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencode()d the data. You'll notice that the & in the URL is replaced by &amp;. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.

I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="foo" />
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from external sources. For example, $_GET['foo_x'].

Note:

Spaces in request variable names are converted to underscores.

How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
The AnotherArray array will now contain the keys 0, 1, email and phone.

Note:

Specifying array keys is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables From External Sources.

How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.

<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

variable = document.forms[0].elements['var[]'];

How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

Example #4 Generating Javascript with PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
// output the geometry variables
echo "Screen width is: ". $_GET['width'] ."<br />\n";
echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
// pass the geometry variables
// (preserve the original query string
// -- post variables will need to handled differently)

echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + screen.width + \"&height=\" + screen.height;\n";
echo "</script>\n";
exit();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


PHP and COM

PHP can be used to access COM and DCOM objects on Win32 platforms.

  1. I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?
  2. What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?
  3. Is it possible manipulate visual objects in PHP ?
  4. Can I store a COM object in a session ?
  5. How can I trap COM errors?
  6. Can I generate DLL files from PHP scripts like I can in Perl ?
  7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
  8. How can I run COM object from remote server ?
  9. I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?
  10. Is it possible to load/manipulate an ActiveX object in a page with PHP ?
  11. Is it possible to get a running instance of a component ?
  12. Is there a way to handle an event sent from COM object ?
  13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?
  14. So PHP works with COM, how about COM+ ?
  15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?
I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?

If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.

What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?

There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.

Is it possible manipulate visual objects in PHP ?

Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.

Can I store a COM object in a session ?

No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.

How can I trap COM errors?

The COM extension throws com_exception exceptions, which you can catch and then inspect the code member to determine what to do next.

Can I generate DLL files from PHP scripts like I can in Perl ?

No, unfortunately there is no such tool available for PHP.

What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?

This error can have multiple reasons:

  • the CLSID is wrong
  • the requested DLL is missing
  • the requested component doesn't implement the IDispatch interface

How can I run COM object from remote server ?

Exactly like you run local objects. You only have to pass the IP of the remote machine as second parameter to the COM constructor.

Make sure that you have set com.allow_dcom =true in your php.ini.

I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?

Edit your php.ini and set com.allow_dcom =true.

Is it possible to load/manipulate an ActiveX object in a page with PHP ?

This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.

Is it possible to get a running instance of a component ?

This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:

<?php
$word = new COM("C:\docs\word.doc");
?>

This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.

Is there a way to handle an event sent from COM object ?

You can define an event sink and bind it using com_event_sink(). You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.

I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?

The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let » me know :)

So PHP works with COM, how about COM+ ?

COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.

If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?

PHP itself doesn't handle transactions yet. Thus if an error occurs no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.

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.


Miscellaneous Questions

There can be some questions we can't put into other categories. Here you can find them.

  1. How can I handle the bz2 compressed manuals on Windows?
How can I handle the bz2 compressed manuals on Windows?

If you don't have an archiver-tool to handle bz2 files » download the command line tool from Redhat (please find further information below).

If you would not like to use a command line tool, you can try free tools like » Stuffit Expander, » UltimateZip, » 7-Zip, or » Quick Zip. If you have tools like » WinRAR or » Power Archiver, you can easily decompress the bz2 files with it. If you use Total Commander (formerly Windows Commander), a bz2 plugin for that program is available freely from the » Total Commander site.

The bzip2 command line tool from Redhat:

Win2k Sp2 users grab the latest version 1.0.2, all other Windows user should grab version 1.00. After downloading rename the executable to bzip2.exe. For convenience put it into a directory in your path, e.g. C:\Windows where C represents your Windows installation drive.

Note: lang stands for your language and x for the desired format, e.g.: pdf. To uncompress the php_manual_lang.x.bz2 follow these simple instructions:

  • open a command prompt window
  • cd to the folder where you stored the downloaded php_manual_lang.x.bz2
  • invoke bzip2 -d php_manual_lang.x.bz2, extracting php_manual_lang.x in the same folder

In case you downloaded the php_manual_lang.tar.bz2 with many html-files in it, the procedure is the same. The only difference is that you got a file php_manual_lang.tar. The tar format is known to be treated with most common archivers on Windows like e.g. » WinZip.

User Contributed Notes

There are no user contributed notes for this page.


Appendices

  • History of PHP and Related Projects
    • History of PHP
    • History of PHP related projects
    • Books about PHP
    • Publications about PHP
  • Migrating from PHP 8.2.x to PHP 8.3.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migrating from PHP 8.1.x to PHP 8.2.x
    • New Features
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migrating from PHP 8.0.x to PHP 8.1.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
  • Migrating from PHP 7.4.x to PHP 8.0.x
    • New Features
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
  • Migrating from PHP 7.3.x to PHP 7.4.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Removed Extensions
    • Other Changes
    • Windows Support
  • Migrating from PHP 7.2.x to PHP 7.3.x
    • New Features
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migrating from PHP 7.1.x to PHP 7.2.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.2.x
    • Other changes
  • Migrating from PHP 7.0.x to PHP 7.1.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.1.x
    • Changed functions
    • Other changes
    • Windows Support
  • Migrating from PHP 5.6.x to PHP 7.0.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 7.0.x
    • Changed functions
    • New functions
    • New Classes and Interfaces
    • New Global Constants
    • Changes in SAPI Modules
    • Removed Extensions and SAPIs
    • Other Changes
  • Migrating from PHP 5.5.x to PHP 5.6.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 5.6.x
    • Changed functions
    • New functions
    • OpenSSL changes in PHP 5.6.x
    • Other changes to extensions
    • New global constants
  • Debugging in PHP
    • About debugging in PHP
  • Configure options
    • List of core configure options
  • php.ini directives
    • List of php.ini directives
    • List of php.ini sections
    • Description of core php.ini directives
  • Extension List/Categorization
    • Alphabetical
    • Membership
    • State
  • List of Function Aliases
  • List of Reserved Words
    • List of Keywords
    • Predefined Classes
    • Predefined Constants
    • List of other reserved words
  • List of Resource Types
  • List of Available Filters
    • String Filters
    • Conversion Filters
    • Compression Filters
    • Encryption Filters
  • List of Supported Socket Transports
    • Internet Domain: TCP, UDP, SSL, and TLS
    • Unix Domain: Unix and UDG
  • PHP type comparison tables
  • List of Parser Tokens
  • Userland Naming Guide
    • Global Namespace
    • Rules
    • Tips
  • About the manual
    • Formats
    • About user notes
    • How to read a function definition (prototype)
    • PHP versions documented in this manual
    • How to find more information about PHP
    • How to help improve the documentation
    • How we generate the formats
    • Translations
  • Creative Commons Attribution 3.0
  • Index listing
    • Function and Method listing
    • Example listing
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


History of PHP and Related Projects

Table of Contents

  • History of PHP
  • History of PHP related projects
  • Books about PHP
  • Publications about PHP

PHP has come a long way since its birth in the mid-1990's. From humble beginnings to becoming one of the most prominent languages powering the web, the evolution of PHP is a geek's fairy tale. Mind you, such explosive growth was no easy task. Those of you interested in briefly seeing how PHP grew to become what it is today, read on. If you'd like to touch a piece of Internet history, you can find old releases of PHP in the » 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


History of PHP

PHP Tools, FI, Construction Kit, and PHP/FI

PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI) binaries written in the C programming language. Originally used for tracking visits to his online resume, he named the suite of scripts "Personal Home Page Tools," more frequently referenced as "PHP Tools." Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and richer implementation. This new model was capable of database interaction and more, providing a framework upon which users could develop simple dynamic web applications such as guestbooks. In June of 1995, Rasmus » released the source code for PHP Tools to the public, which allowed developers to use it as they saw fit. This also permitted - and encouraged - users to provide fixes for bugs in the code, and to generally improve upon it.

In September of that year, Rasmus expanded upon PHP and - for a short time - actually dropped the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new implementation included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables, and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. In fact, to embed the code into an HTML file, developers had to use HTML comments. Though this method was not entirely well-received, FI continued to enjoy growth and acceptance as a CGI tool --- but still not quite as a language. However, this began to change the following month; in October, 1995, Rasmus released a complete rewrite of the code. Bringing back the PHP name, it was now (briefly) named "Personal Home Page Construction Kit," and was the first release to boast what was, at the time, considered an advanced scripting interface. The language was deliberately designed to resemble C in structure, making it an easy adoption for developers familiar with C, Perl, and similar languages. Having been thus far limited to UNIX and POSIX-compliant systems, the potential for a Windows NT implementation was being explored.

The code got another complete makeover, and in April of 1996, combining the names of past releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly evolve PHP from a suite of tools into a programming language in its own right. It included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support, and much more. That June, PHP/FI was given a version 2.0 status. An interesting fact about this, however, is that there was only one single full version of PHP 2.0. When it finally graduated from beta status in November, 1997, the underlying parsing engine was already being entirely rewritten.

Though it lived a short development life, it continued to enjoy a growing popularity in still-young world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users around the world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains reported having headers containing "PHP", indicating that the host server did indeed have it installed. This number equated to approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was still primarily developed by an individual.

Example #1 Example PHP/FI Code

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding PHP/FI 2.0 still inefficient and lacking features they needed to power an eCommerce application they were developing for a university project, Andi Gutmans and Zeev Suraski of Tel Aviv, Israel, began yet another complete rewrite of the underlying parser in 1997. Approaching Rasmus online, they discussed various aspects of the current implementation and their redevelopment of PHP. In an effort to improve the engine and start building upon PHP/FI's existing user base, Andi, Rasmus, and Zeev decided to collaborate in the development of a new, independent programming language. This entirely new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP', with the meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a mature interface for multiple databases, protocols, and APIs, the ease of extending the language itself attracted dozens of developers who submitted a variety of modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 included object-oriented programming support and a far more powerful and consistent language syntax.

In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was announced by the new PHP Development Team as the official successor to PHP/FI 2.0. Active development of PHP/FI 2.0, which had all-but ceased as of November of the previous year, was now officially ended. After roughly nine months of open public testing, when the announcement of the official release of PHP 3.0 came, it was already installed on over 70,000 domains around the world, and was no longer limited to POSIX-compliant operating systems. A relatively small share of the domains reporting PHP as installed were hosted on servers running Windows 95, 98, and NT, and Macintosh. At its peak, PHP 3.0 was installed on approximately 10% of the web servers on the Internet.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related and supporting projects, such as PEAR, PECL, and documentation, and an underlying network infrastructure of well over one-hundred individual web servers on six of the seven continents of the world. Though only an estimate based upon statistics from previous years, it is safe to presume PHP is now installed on tens or even perhaps hundreds of millions of domains around the world.

User Contributed Notes

There are no user contributed notes for this page.


History of PHP related projects

PEAR

» PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in » the manual.

PHP Quality Assurance Initiative

The » PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.

PHP-GTK

» PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.

User Contributed Notes

There are no user contributed notes for this page.


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' (PHP - Creating Interactive Internet Applications) - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. These books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 400 books in English, over 100 books in German, and over 50 books in French or Spanish! In addition, you can find books about PHP in many other languages, including Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.

User Contributed Notes

There are no user contributed notes for this page.


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 8.2.x to PHP 8.3.x

Table of Contents

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Readonly Amendments

Anonymous classes may now be marked as readonly.

Readonly properties can now be reinitialized during cloning.

Typed Class Constants

Class, interface, trait, and enum constants now support type declarations.

Closures created from magic methods

Closures created from magic methods can now accept named arguments.

The final modifier with a method from a trait

The final modifier may now be used when using a method from a trait.

Override Attribute

Added the #[\Override] attribute to check that a method exists in a parent class or implemented interface.

Fetch class constant dynamically syntax

Class constants can now be accessed dynamically using the C::{$name} syntax.

Static variable Initializers

Static variable initializers can now contain arbitrary expressions.

Fallback value syntax for ini variables

php.ini now supports fallback/default value syntax.

<?php
/*
On /path/to/user.ini contains the following settings:

listen = localhost:${DRUPAL_FPM_PORT:-9000}
*/

$user_ini = parse_ini_file('/path/to/user.ini');
echo $user_ini['listen']; // localhost:9000

CLI

It is now possible to lint multiple files.

DOM

Added properties DOMElement::$className and DOMElement::$id. These are not binary-safe at the moment because of underlying limitations of libxml2. This means that the property values will be cut off at a NUL byte.

Added properties DOMNode::$isConnected and DOMNameSpaceNode::$isConnected.

Added properties DOMNode::$parentElement and DOMNameSpaceNode::$parentElement.

FFI

It is now possible to assign FFI\CData to other FFI\CData. Meaning CData can now be assigned to structs and fields.

Opcache

opcache_get_status()['scripts'][n]['revalidate'] now contains a Unix timestamp of when the next revalidation of the scripts timestamp is due, dictated by the opcache.revalidate_freq INI directive.

POSIX

posix_getrlimit() now takes an optional $res parameter to allow fetching a single resource limit.

posix_isatty() now raises type warnings for integers following the usual ZPP semantics.

posix_ttyname() now raises type warnings for integers following the usual ZPP semantics and value warnings for invalid file descriptor integers.

Streams

Streams can now emit the STREAM_NOTIFY_COMPLETED notification. This was previously not implemented.

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

Date

  • DateError
  • DateObjectError
  • DateRangeError
  • DateException
  • DateInvalidOperationException
  • DateInvalidTimeZoneException
  • DateMalformedIntervalStringException
  • DateMalformedPeriodStringException
  • DateMalformedStringException

Random

  • Random\IntervalBoundary

User Contributed Notes

There are no user contributed notes for this page.


New Functions

Date

  • DatePeriod::createFromISO8601String()

DOM

  • DOMElement::getAttributeNames()
  • DOMElement::insertAdjacentElement()
  • DOMElement::insertAdjacentText()
  • DOMElement::toggleAttribute()
  • DOMNode::contains()
  • DOMNode::getRootNode()
  • DOMNode::isEqualNode()
  • DOMNameSpaceNode::contains()
  • DOMParentNode::replaceChildren()

Intl

  • IntlCalendar::setDate()
  • IntlCalendar::setDateTime()
  • IntlGregorianCalendar::createFromDate()
  • IntlGregorianCalendar::createFromDateTime()

JSON

  • json_validate()

LDAP

  • ldap_connect_wallet()
  • ldap_exop_sync()

MBString

  • mb_str_pad()

Posix

  • posix_sysconf()
  • posix_pathconf()
  • posix_fpathconf()
  • posix_eaccess()

PostgreSQL

  • pg_set_error_context_visibility() (libpq >= 9.6)

Random

  • Random\Randomizer::getBytesFromString()
  • Random\Randomizer::nextFloat()
  • Random\Randomizer::getFloat()

Reflection

  • ReflectionMethod::createFromMethodName()

Sockets

  • socket_atmark()

Standard

  • str_increment()
  • str_decrement()
  • stream_context_set_options()

Zip

  • ZipArchive::getArchiveFlag()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLINFO_CAPATH (libcurl >= 7.84.0)
  • CURLINFO_CAINFO (libcurl >= 7.84.0)
  • CURLOPT_MIME_OPTIONS (libcurl >= 7.81.0)
  • CURLMIMEOPT_FORMESCAPE (libcurl >= 7.81.0)
  • CURLOPT_WS_OPTIONS (libcurl >= 7.86.0)
  • CURLWS_RAW_MODE (libcurl >= 7.86.0)
  • CURLOPT_SSH_HOSTKEYFUNCTION (libcurl >= 7.84.0)
  • CURLOPT_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_REDIR_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_CA_CACHE_TIMEOUT (libcurl >= 7.87.0)
  • CURLOPT_QUICK_EXIT (libcurl >= 7.87.0)
  • CURLKHMATCH_OK (libcurl >= 7.19.6)
  • CURLKHMATCH_MISMATCH (libcurl >= 7.19.6)
  • CURLKHMATCH_MISSING (libcurl >= 7.19.6)
  • CURLKHMATCH_LAST (libcurl >= 7.19.6)

Intl

  • MIXED_NUMBERS (Spoofchecker)
  • HIDDEN_OVERLAY (Spoofchecker)

OpenSSL

  • OPENSSL_CMS_OLDMIMETYPE
  • PKCS7_NOOLDMIMETYPE

PCNTL

  • SIGINFO

PDO_ODBC

  • PDO_ODBC_TYPE

Posix

  • POSIX_SC_ARG_MAX
  • POSIX_SC_PAGESIZE
  • POSIX_SC_NPROCESSORS_CONF
  • POSIX_SC_NPROCESSORS_ONLN
  • POSIX_PC_LINK_MAX
  • POSIX_PC_MAX_CANON
  • POSIX_PC_MAX_INPUT
  • POSIX_PC_NAME_MAX
  • POSIX_PC_PATH_MAX
  • POSIX_PC_PIPE_BUF
  • POSIX_PC_CHOWN_RESTRICTED
  • POSIX_PC_NO_TRUNC
  • POSIX_PC_ALLOC_SIZE_MIN
  • POSIX_PC_SYMLINK_MAX

Sockets

The following socket options are now defined if they are supported:

  • SO_ATTACH_REUSEPORT_CBPF (Linux)
  • SO_DETACH_BPF (Linux)
  • SO_DETACH_FILTER (Linux)
  • TCP_QUICKACK (Linux)
  • IP_DONTFRAG (FreeBSD)
  • IP_MTU_DISCOVER (Linux)
  • IP_PMTUDISC_DO (Linux)
  • IP_PMTUDISC_DONT (Linux)
  • IP_PMTUDISC_WANT (Linux)
  • IP_PMTUDISC_PROBE (Linux)
  • IP_PMTUDISC_INTERFACE (Linux)
  • IP_PMTUDISC_OMIT (Linux)
  • AF_DIVERT (FreeBSD)
  • SOL_UDPLITE
  • UDPLITE_RECV_CSCOV
  • UDPLITE_SEND_CSCOV
  • SO_RERROR (NetBSD)
  • SO_ZEROIZE (OpenBSD)
  • SO_SPLICE (OpenBSD)
  • TCP_REPAIR (Linux)
  • SO_REUSEPORT_LB (FreeBSD)
  • IP_BIND_ADDRESS_NO_PORT (Linux)

Zip

  • ZipArchive::ER_DATA_LENGTH (libzip >= 1.10)
  • ZipArchive::ER_NOT_ALLOWED (libzip >= 1.10)
  • ZipArchive::AFL_RDONLY (libzip >= 1.10)
  • ZipArchive::AFL_IS_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_WANT_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE (libzip >= 1.10)
  • ZipArchive::FL_OPEN_FILE_NOW
  • ZipArchive::LENGTH_TO_END as default value for
ZipArchive::addFile() and
ZipArchive::replaceFile()
  • ZipArchive::LENGTH_UNCHECKED (libzip >= 1.10)

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Programs that were very close to overflowing the call stack

Programs that were very close to overflowing the call stack may now throw an Error when using more than zend.max_allowed_stack_size-zend.reserved_stack_size bytes of stack (fiber.stack_size-zend.reserved_stack_size for fibers).

Executing proc_get_status() multiple times

Executing proc_get_status() multiple times will now always return the right value on POSIX systems. Previously, only the first call of the function returned the right value. Executing proc_close() after proc_get_status() will now also return the right exit code. Previously this would return -1. Internally, this works by caching the result on POSIX systems. If the previous behaviour is required, it is possible to check the "cached" key in the array returned by proc_get_status() to check whether the result was cached.

Zend Max Execution Timers

Zend Max Execution Timers is now enabled by default for ZTS builds on Linux.

Uses of traits with static properties

Uses of traits with static properties will now redeclare static properties inherited from the parent class. This will create a separate static property storage for the current class. This is analogous to adding the static property to the class directly without traits.

Assigning a negative index to an empty array

Assigning a negative index $n to an empty array will now make sure that the next index is $n+1 instead of 0.

Class constant visibility variance check

Class constant visibility variance is now correctly checked when inherited from interfaces.

WeakMap entries whose key maps to itself

WeakMap entries whose key maps to itself (possibly transitively) may now be removed during cycle collection if the key is not reachable except by iterating over the WeakMap (reachability via iteration is considered weak). Previously, such entries would never be automatically removed.

Date

The DateTime extension has introduced Date extension specific exceptions and errors under the DateError and DateException hierarchies, instead of warnings and generic exceptions. This improves error handling, at the expense of having to check for errors and exceptions.

DOM

Calling DOMChildNode::after(),
DOMChildNode::before(),
DOMChildNode::replaceWith()
on a node that has no parent is now a no-op instead of a hierarchy
exception, which is the behaviour demanded by the DOM specification.

Using the DOMParentNode and DOMChildNode methods without a document now works instead of throwing a DOM_HIERARCHY_REQUEST_ERR DOMException. This is in line with the behaviour demanded by the DOM specification.

Calling DOMDocument::createAttributeNS() without specifying a prefix would incorrectly create a default namespace, placing the element inside the namespace instead of the attribute. This bug is now fixed.

DOMDocument::createAttributeNS() would previously incorrectly throw a DOM_NAMESPACE_ERRNAMESPACE_ERR DOMException when the prefix was already used for a different URI. It now correctly chooses a different prefix when there's a prefix name conflict.

New methods and properties were added to some DOM classes. If a userland class inherits from these classes and declare a method or property with the same name, the declarations must be compatible. Otherwise, a typical compile error about incompatible declarations will be thrown. See the list of new features and new functions for a list of the newly implemented methods and properties.

FFI

C functions that have a return type of void now return null instead of returning the following object object(FFI\CData:void) { }

Opcache

The opcache.consistency_checks INI directive was removed. This feature was broken with the tracing JIT, as well as with inheritance cache, and has been disabled without a way to enable it since PHP 8.1.18 and PHP 8.2.5. Both the tracing JIT and inheritance cache may modify shm after the script has been persisted by invalidating its checksum. The attempted fix skipped over the modifiable pointers but was rejected due to complexity. For this reason, it was decided to remove the feature instead.

Phar

The type of Phar class constants are now declared.

Standard

The range() function has had various changes:

  • A TypeError is now thrown when passing objects, resources, or arrays as the boundary inputs.
  • A more descriptive ValueError is thrown when passing 0 for $step.
  • A ValueError is now thrown when using a negative $step for increasing ranges.
  • If $step is a float that can be interpreted as an int, it is now done so.
  • A ValueError is now thrown if any argument is infinity or NAN.
  • An E_WARNING is now emitted if $start or $end is the empty string. The value continues to be cast to the value 0.
  • An E_WARNING is now emitted if $start or $end has more than one byte, only if it is a non-numeric string.
  • An E_WARNING is now emitted if $start or $end is cast to an integer because the other boundary input is a number. (e.g. range(5, 'z');).
  • An E_WARNING is now emitted if $step is a float when trying to generate a range of characters, except if both boundary inputs are numeric strings (e.g. range('5', '9', 0.5); does not produce a warning).
  • range() now produce a list of characters if one of the boundary inputs is a string digit instead of casting the other input to int (e.g. range('9', 'A');).
<?php
range('9', 'A'); // ["9", ":", ";", "<", "=", ">", "?", "@", "A"], as of PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], prior to PHP 8.3.0
?>

The file() flags error check now catches all invalid flags. Notably FILE_APPEND was previously silently accepted.

SNMP

The type of SNMP class constants are now declared.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Saner Increment/Decrement operators

Using the increment operator (++) on empty, non-numeric, or non-alphanumeric strings is now deprecated. Moreover, incrementing non-numeric strings is soft deprecated. That means no E_DEPRECATED diagnostic is emitted, but this feature should not be used when producing new code. The new str_increment() function should be used instead.

Using the decrement operator (--) on empty or non-numeric strings is now deprecated.

get_class()/get_parent_class() call without arguments

Calling get_class() and get_parent_class() without arguments is now deprecated.

DBA

Calling dba_fetch() with $dba as the 3rd argument is now deprecated.

FFI

Calling FFI::cast(), FFI::new(), and FFI::type() statically is now deprecated.

Intl

The U_MULTIPLE_DECIMAL_SEP*E*RATORS constant had been deprecated, using the U_MULTIPLE_DECIMAL_SEP*A*RATORS constant instead is recommended.

The NumberFormatter::TYPE_CURRENCY constant has been deprecated.

LDAP

Calling ldap_connect() with separate $hostname and $port is deprecated.

MBString

Passing a negative $width to mb_strimwidth() is now deprecated.

Phar

Calling Phar::setStub() with a resource and a $length is now deprecated. Such calls should be replaced by: $phar->setStub(stream_get_contents($resource));

Random

The MT_RAND_PHP Mt19937 variant is deprecated.

Reflection

Calling ReflectionProperty::setValue() with only one parameter is deprecated. To set static properties, pass null as the first parameter.

Standard

The assert_options() function is now deprecated.

The ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION, and ASSERT_WARNING constants have been deprecated.

The assert.* INI settings have been deprecated. See the Changes to INI File Handling page for further details.

SQLite3

Using exceptions is now preferred, warnings will be removed in the future. Calling SQLite3::enableExceptions(false) will trigger a deprecation warning in this version.

Zip

The ZipArchive::FL_RECOMPRESS constant is deprecated and will be removed in a future version of libzip.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Core changes

FFI

FFI::load() is now allowed during preloading when opcache.preload_user is the current system user. Previously, calling FFI::load() was not possible during preloading if the opcache.preload_user directive was set.

FPM

FPM CLI test now fails if the socket path is longer than supported by OS.

Opcache

In the CLI and phpdbg SAPIs, preloading does not require the opcache.preload_user directive to be set anymore when running as root. In other SAPIs, this directive is required when running as root because preloading is done before the SAPI switches to an unprivileged user.

Streams

Blocking fread() on socket connection returns immediately if there are any buffered data instead of waiting for more data.

Memory stream no longer fails if seek offset is past the end. Instead the memory is increase on the next write and date between the old end and offset is filled with zero bytes in the same way how it works for files.

stat() access operations like file_exists() and similar will now use real path instead of the actual stream path. This is consistent with stream opening.

Changes in SAPI Modules

CLI

The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using fclose() and similar.

Changed Functions

Core

gc_status() has added the following 8 fields:

  • "running" => bool
  • "protected" => bool
  • "full" => bool
  • "buffer_size" => int
  • "application_time" => float: Total application time, in seconds (including collector_time)
  • "collector_time" => float: Time spent collecting cycles, in seconds (including destructor_time and free_time)
  • "destructor_time" => float: Time spent executing destructors during cycle collection, in seconds
  • "free_time" => float: Time spent freeing values during cycle collection, in seconds

class_alias() now supports creating an alias of an internal class.

Setting open_basedir at runtime using ini_set('open_basedir', ...); no longer accepts paths containing the parent directory (..). Previously, only paths starting with .. were disallowed. This could easily be circumvented by prepending ./ to the path.

User exception handlers now catch exceptions during shutdown.

The resultant HTML of highlight_string() and highlight_file() has changed. Whitespace between outer HTML tags is removed. Newlines and spaces are no longer converted to HTML entities. The whole HTML is now wrapped in a <pre> tag. The outer <span> tag has been merged with the <code> tag.

Calendar

easter_date() now supports years from 1970 to 2,000,000,000 on 64-bit systems, previously it only supported years in the range from 1970 to 2037.

Curl

curl_getinfo() now supports two new constants: CURLINFO_CAPATH and CURLINFO_CAINFO. If option is null, the following two additional keys are present: "capath" and "cainfo".

DOM

Changed DOMCharacterData::appendData() tentative return type to true.

DOMDocument::loadHTML(), DOMDocument::loadHTMLFile(), and DOMDocument::loadXML() now have a tentative return type of bool. Previously, this was documented as having a return type of DOMDocument|bool, but, as of PHP 8.0.0, DOMDocument cannot be returned as it is no longer statically callable.

Gd

The signature of imagerotate() has changed. The $ignore_transparent parameter has been removed, as it was ignored since PHP 5.5.0.

Intl

datefmt_set_timezone() (and its alias IntlDateformatter::setTimeZone()) now returns true on success, previously null was returned.

IntlBreakiterator::setText() now returns false on failure, previously null was returned. It now returns true on success, previously null was returned.

IntlChar::enumCharNames() is now returning a boolean. Previously it returned null on success and false on failure.

IntlDateFormatter::__construct() throws an U_ILLEGAL_ARGUMENT_ERROR exception when an invalid locale had been set.

MBString

mb_strtolower() and mb_convert_case() implement conditional casing rules for the Greek letter sigma. For mb_convert_case(), conditional casing only applies to MB_CASE_LOWER and MB_CASE_TITLE modes, not to MB_CASE_LOWER_SIMPLE and MB_CASE_TITLE_SIMPLE.

mb_decode_mimeheader() interprets underscores in QPrint-encoded MIME encoded words as required by RFC 2047; they are converted to spaces. Underscores must be encoded as "=5F" in such MIME encoded words.

In rare cases, mb_encode_mimeheader() will transfer-encode its input string where it would pass it through as raw ASCII in PHP 8.2.

mb_encode_mimeheader() no longer drops NUL (zero) bytes when QPrint-encoding the input string. This previously caused strings in certain text encodings, especially UTF-16 and UTF-32, to be corrupted by mb_encode_mimeheader.

mb_detect_encoding()'s "non-strict" mode now behaves as described in the documentation. Previously, it would return false if the same byte (for example, the first byte) of the input string was invalid in all candidate encodings. More generally, it would eliminate candidate encodings from consideration when an invalid byte was seen, and if the same input byte eliminated all remaining encodings still under consideration, it would return false. On the other hand, if all candidate encodings but one were eliminated from consideration, it would return the last remaining one without regard for how many encoding errors might be encountered later in the string. This is different from the behavior described in the documentation, which says: "If strict is set to false, the closest matching encoding will be returned."

mysqli

mysqli_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

mysqli_poll() now raises a ValueError when neither the $read nor the $error arguments are passed.

mysqli_field_seek() and mysqli_result::field_seek() now specify the return type as true instead of bool.

ODBC

odbc_autocommit() now accepts null for the $enable parameter. Passing null has the same behaviour as passing only 1 parameter, namely indicating if the autocommit feature is enabled or not.

PGSQL

pg_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

pg_insert() now raises a ValueError instead of a E_WARNING when the table specified is invalid.

pg_insert() and pg_convert() raises a ValueError or a TypeError instead of a E_WARNING when the value/type of a field does not match properly with a PostgreSQL's type.

The $row parameter of
pg_fetch_result(),
pg_field_prtlen(), and
pg_field_is_null() is now nullable.

Random

Changed mt_srand() and srand() to not check the number of arguments to determine whether a random seed should be used. Passing null will generate a random seed, 0 will use zero as the seed. The functions are now consistent with Random\Engine\Mt19937::__construct().

Reflection

Return type of ReflectionClass::getStaticProperties() is no longer nullable.

Standard

E_NOTICEs emitted by unserialize() have been promoted to E_WARNING.

unserialize() now emits a new E_WARNING if the input contains unconsumed bytes.

array_pad() is now only limited by the maximum number of elements an array can have. Before, it was only possible to add at most 1048576 elements at a time.

strtok() raises an E_WARNING in the case token is not provided when starting tokenization.

password_hash() will now chain the underlying Random\RandomException as the ValueError's $previous Exception when salt generation fails.

If using an array as the $command for proc_open(), it must now have at least one non empty element. Otherwise a ValueError is thrown.

proc_open() returns false if $command array is invalid command instead of resource object that produces warning later. This was already the case for Windows but it is now also the case if posix_spawn implementation is in use (most Linux, BSD and MacOS platforms). There are still some old platforms where this behavior is not changed as posix_spawn is not supported there.

array_sum() and array_product() now warn when values in the array cannot be converted to int/float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now casted instead of ignored.

The $decimal of number_format() now properly handles negative integers. Rounding with a negative value for $decimal means that $num is rounded to $decimals significant digits before the decimal point. Previously negative $decimals were silently ignored and the number got rounded to zero decimal places.

A new $before_needle argument has been added to strrchr(). It behaves like its counterpart in the strstr() or stristr() functions.

str_getcsv() and fgetcsv() now return an empty string instead of a string with a single null byte for the last field which only contains an unterminated enclosure.

Other Changes to Extensions

Core

Using the increment/decrement operators (++/--) on values of type bool now emit warnings. This is because it currently has no effect, but will behave like $bool += 1 in the future.

Using the decrement operator (--) on values of type null now emit warnings. This is because it currently has no effect, but will behave like $null -= 1 in the future.

Internal objects that implement an _IS_NUMBER cast but not a do_operator handler that overrides addition and subtraction now can be incremented and decrement as if one would do $o += 1 or $o -= 1

DOM

The DOM lifetime mechanism has been reworked such that implicitly removed nodes can still be fetched. Previously this resulted in an exception.

SQLite3

The SQLite3 class now throws SQLite3Exception (extends Exception) instead of Exception.

The SQLite error code is now passed in the exception error code instead of being included in the error message.

Changes to INI File Handling

  • The assert.* INI settings have been deprecated. This comprises the following INI settings:

    • assert.active
    • assert.bail
    • assert.callback
    • assert.exception
    • assert.warning
    If the value of the setting is equal to the default value, no deprecation notice is emitted. The zend.assertions INI setting should be used instead.

  • zend.max_allowed_stack_size is a new INI directive to set the maximum allowed stack size. Possible values are 0 (detect the process or thread maximum stack size), -1 (no limit), or a positive number of bytes. The default is 0. When it is not possible to detect the process or thread maximum stack size, a known system default is used. Setting this value too high has the same effect as disabling the stack size limit. Fibers use fiber.stack_size as maximum allowed stack size. An Error is thrown when the process call stack exceeds zend.max_allowed_stack_size-zend.reserved_stack_size bytes, to prevent stack-overflow-induced segmentation faults, with the goal of making debugging easier. The stack size increases during uncontrolled recursions involving internal functions or the magic methods __toString(), __clone(), __sleep(), __destruct(). This is not related to stack buffer overflows, and is not a security feature.

  • zend.reserved_stack_size is a new INI directive to set the reserved stack size, in bytes. This is subtracted from the max allowed stack size, as a buffer, when checking the stack size.

Performance

DOM

Looping over a DOMNodeList now uses caching. Therefore requesting items no longer takes quadratic time by default.

Getting text content from nodes now avoids an allocation, resulting in a performance gain.

DOMChildNode::remove() now runs in O(1) performance.

Standard

The file() flags error check is now about 7% faster.

SPL

RecursiveDirectoryIterator now performs less I/O when looping over a directory.

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

Core

Minimum supported Windows version has been bumped to Windows 8 or Windows Server 2012.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 8.1.x to PHP 8.2.x

Table of Contents

  • New Features
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x.

User Contributed Notes

Anonymous 03-Mar-2023 01:02
that’s incredible version of PHP,The performance is really nicer than older version.


New Features

PHP Core

SensitiveParameter Attribute

Added the #[\SensitiveParameter] attribute to redact sensitive data in backtraces.

error_log_mode INI directive

The error_log_mode INI directive has been added which allows setting the permissions for the error log file.

Enumerations properties in constant expressions

It is now possible to fetch properties of Enumerations in constant expressions.

Type System Improvements

It is now possible to use null and false as stand-alone types.

The true type has been added.

It is now possible to combine intersection and union types. The type needs to be written in DNF.

Constants in Traits

It is now possible to define constants in traits.

Readonly Classes

Support for readonly on classes has been added.

cURL

Added the CURLINFO_EFFECTIVE_METHOD option, which returns the effective HTTP method in the return value of curl_getinfo().

Exposed multiple new constants from libcurl 7.62 to 7.80.

Added the curl_upkeep() function to perform any connection upkeep checks.

DBA

The LMDB Driver now accepts the DBA_LMDB_USE_SUB_DIR or DBA_LMDB_NO_SUB_DIR flags to determine if it should create a subdirectory or not when creating a database file.

OCI8

Added the oci8.prefetch_lob_size INI directive and oci_set_prefetch_lob() function to tune LOB query performance by reducing the number of round-trips between PHP and Oracle Databases when fetching LOBS. This is usable with Oracle Database 12.2 or later.

OpenSSL

Added AEAD support for the chacha20-poly1305 algorithm.

ODBC

Added the odbc_connection_string_is_quoted(), odbc_connection_string_should_quote(), and odbc_connection_string_quote() functions. These are primarily used behind the scenes in the ODBC and PDO_ODBC extensions, but are exposed to userland for easier unit testing, and for user applications and libraries to perform quoting themselves.

PCRE

Added support for the n (NO_AUTO_CAPTURE) modifier, which makes simple (xyz) groups non-capturing. Only named groups like (?<name>xyz) are capturing. This only affects which groups are capturing, it is still possible to use numbered subpattern references, and the matches array will still contain numbered results.

Random

This is a new extension which organises and consolidates existing implementations related to random number generators. New and better RNGs are available with scope issues eliminated.

User Contributed Notes

There are no user contributed notes for this page.


New Functions

cURL

  • curl_upkeep()

IMAP

  • imap_is_open() (as of PHP 8.2.1)

MySQLi

  • mysqli_execute_query()

ODBC

  • odbc_connection_string_is_quoted()
  • odbc_connection_string_should_quote()
  • odbc_connection_string_quote()

OpenSSL

  • openssl_cipher_key_length()

Reflection

  • ReflectionFunction::isAnonymous()
  • ReflectionMethod::hasPrototype()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20_xor_ic()

Standard

  • memory_reset_peak_usage()
  • ini_parse_quantity()

XML

  • libxml_get_external_entity_loader()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

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

The following socket options are now defined if they are supported:

  • SO_INCOMING_CPU
  • SO_MEMINFO
  • SO_RTABLE (OpenBSD)
  • TCP_KEEPALIVE (MacOS)
  • TCP_KEEPCNT (Linux, others)
  • TCP_KEEPIDLE (Linux, others)
  • TCP_KEEPINTVL (Linux, others)
  • TCP_NOTSENT_LOWAT
  • LOCAL_CREDS_PERSISTENT (FreeBSD)
  • SCM_CREDS2 (FreeBSD)
  • LOCAL_CREDS (NetBSD)
  • SO_BPF_EXTENSIONS
  • SO_SETFIB
  • TCP_CONGESTION (Linux, FreeBSD)
  • SO_ZEROCOPY (Linux)
  • MSG_ZEROCOPY (Linux)

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

Date

DateTime::createFromImmutable() now has a tentative return type of static, previously it was DateTime.

DateTimeImmutable::createFromMutable() now has a tentative return type of static, previously it was DateTimeImmutable.

number symbols in relative formats no longer accept multiple signs, e.g. +-2.

ODBC

The ODBC extension now escapes the username and password for the case when both a connection string and username/password are passed, and the string must be appended to. Before, user values containing values needing escaping could have created a malformed connection string, or injected values from user-provided data. The escaping rules should be identical to the .NET BCL DbConnectionOptions behaviour.

PDO_ODBC

The PDO_ODBC extension also escapes the username and password when a connection string is passed. See the change to the ODBC extension for further details.

Standard

glob() now returns an empty array if all paths are restricted by open_basedir. Previously it returned false. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.

FilesystemIterator::__construct(): prior to PHP 8.2.0, FilesystemIterator::SKIP_DOTS constant was always set and couldn't be disabled. In order to maintain the previous behaviour the constant must be explicitly set when using the flags parameter. The default value from flags parameter has not been modified.

strtolower(),
strtoupper(),
stristr(),
stripos(),
strripos(),
lcfirst(),
ucfirst(),
ucwords(),
and str_ireplace() are no longer locale-sensitive.
They now perform ASCII case conversion, as if the locale were "C".
Localized versions of these functions are available in the MBString extension.
Moreover, array_change_key_case(), and sorting with
SORT_FLAG_CASE now also use ASCII case conversion.

str_split() returns an empty array for an empty string now. Previously it returned an array with a single empty string entry. mb_str_split() is not affected by this change as it was already behaving like that.

ksort() and krsort() now do numeric string comparison under SORT_REGULAR using the standard PHP 8 rules now.

var_export() no longer omits the leading backslash for exported classes, i.e. these are now fully qualified.

Standard PHP Library (SPL)

The following methods now enforce their signature:

  • SplFileInfo::_bad_state_ex()
  • SplFileObject::getCsvControl()
  • SplFileObject::fflush()
  • SplFileObject::ftell()
  • SplFileObject::fgetc()
  • SplFileObject::fpassthru()

SplFileObject::hasChildren() now has a tentative return type of false, previously it was bool.

SplFileObject::getChildren() now has a tentative return type of null, previously it was ?RecursiveIterator.

GlobIterator now returns an empty array if all paths are restricted by open_basedir. Previously it returned false. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Usage of dynamic properties

The creation of dynamic properties is deprecated, unless the class opts in by using the #[\AllowDynamicProperties] attribute. stdClass allows dynamic properties. Usage of the __get()/__set() magic methods is not affected by this change. A dynamic properties deprecation warning can be addressed by:

  • Declaring the property (preferred).
  • Adding the #[\AllowDynamicProperties] attribute to the class (which also applies to all child classes).
  • Using a WeakMap if additional data needs to be associated with an object which one does not own.

Relative callables

Callables that are not accepted by the $callable() syntax (but are accepted by call_user_func()) are deprecated. In particular:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
This does not affect normal method callables such as "A::method" or ["A", "method"].

"${var}" and "${expr}" style interpolation

The "${var}" and "${expr}" style of string interpolation is deprecated. Use "$var"/"{$var}" and "{${expr}}", respectively.

MBString

Usage of the QPrint, Base64, Uuencode, and HTML-ENTITIES 'text encodings' is deprecated for all MBString functions. Unlike all the other text encodings supported by MBString, these do not encode a sequence of Unicode codepoints, but rather a sequence of raw bytes. It is not clear what the correct return values for most MBString functions should be when one of these non-encodings is specified. Moreover, PHP has separate, built-in implementations of all of them; for example, UUencoded data can be handled using convert_uuencode()/convert_uudecode().

SPL

The internal SplFileInfo::_bad_state_ex() method has been deprecated.

Standard

utf8_encode() and utf8_decode() have been deprecated.

User Contributed Notes

tabflo at gmx dot at 13-Jul-2023 01:43
a have a baseclass for all databasemodels and handle my dynamic property setter and getter this way:

    public array $dynamicProperties = [];

    public function __set(string $name, mixed $value) {
        if(property_exists($this, $name))
            $this->{$name} = $value;
        else
            $this->dynamicProperties[$name] = $value;
    }

    public function __get(string $name) {
        if(property_exists($this, $name))
            return $this->$name;
        else
            return $this->dynamicProperties[$name];
    }

just put the content into a class and extend from it. enjoy :)


Other Changes

Core changes

The iterable type is now a built-in compile time alias for array|Traversable. Error messages relating to iterable will therefore now use array|Traversable. Type Reflection is preserved for single iterable (and ?iterable) to produce a ReflectionNamedType with name iterable, however usage of iterable in union types will be converted to array|Traversable.

The date format of sent cookies is now 'D, d M Y H:i:s \G\M\T'; previously it was 'D, d-M-Y H:i:s T'.

Changes in SAPI Modules

CLI

The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using fclose() and similar.

Changed Functions

Core

The strcmp(), strcasecmp(),
strncmp(), strncasecmp(), and
substr_compare() functions, using binary safe string
comparison now return -1, 0 and 1.

DBA

dba_open() and dba_popen() now have the following enforced signature:

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

dba_fetch()'s optional skip argument is now at the end in line with PHP userland semantics. Its signature is now:

dba_fetch(string|array $key, resource $handle, int $skip): string|false
The overloaded signature:
dba_fetch(string|array $key, int $skip, resource $handle): string|false
is still accepted, but it is recommended to use the new standard variant.

Random

random_bytes() and random_int() now throw a \Random\RandomException on CSPRNG failures. Previously a plain \Exception was thrown instead.

SPL

The iterator parameter of iterator_to_array() and iterator_count() is widened to iterable from Iterator, allowing arrays to be passed.

Other Changes to Extensions

Date

The properties of DatePeriod are now properly declared.

Intl

Instances of IntlBreakIterator, IntlRuleBasedBreakIterator, IntlCodePointBreakIterator, IntlPartsIterator, IntlCalendar, Collator, IntlIterator, UConverter, IntlDateFormatter, IntlDatePatternGenerator, MessageFormatter, ResourceBundle, Spoofchecker, IntlTimeZone, and Transliterator are no longer serializable. Previously, they could be serialized, but unserialization yielded unusable objects or failed.

MySQLi

The support for libmysql has been removed and it is no longer possible to compile mysqli with libmysql. From now on, the mysqli extension can be compiled only with mysqlnd. All libmysql features unavailable in mysqlnd have been removed:

  • The reconnect property of mysqli_driver
  • The mysqli.reconnect INI directive
  • The MYSQLI_IS_MARIADB constant has been deprecated

OCI8

The minimum Oracle Client library version required is now 11.2.

PCRE

NUL characters (\0) in pattern strings are now supported.

Session

Trying to change the session.cookie_samesite INI directive while the session is active or output has already been sent will now fail and emit a warning. This aligns the behaviour with all other session INI settings.

SQLite3

sqlite3.defensive is now PHP_INI_USER.

Standard

getimagesize() now reports the actual image dimensions, bits and channels of AVIF images. Previously, the dimensions have been reported as 0x0, and bits and channels have not been reported at all.

Tidy

The properties of the tidy class are now properly declared. And those of the tidyNode class are now properly declared as readonly.

Zip

The Zip extension has been updated to version 1.20.0, which adds the following methods:

  • ZipArchive::clearError()
  • ZipArchive::getStreamName()
  • ZipArchive::getStreamIndex()

Changes to INI File Handling

Support for binary (0b/0B) and octal (0o/0O) prefixes has been added to integer INI settings. Integer INI settings that start with a zero (0) continue to be interpreted as an octal integer.

Parsing of some ill-formatted values will now trigger a warning when this was silently ignored before. For backwards compatibility, interpretation of these values has not changed. This affects the following settings:

  • bcmath.scale
  • com.code_page
  • default_socket_timeout
  • fiber.stack_size
  • hard_timeout
  • intl.error_level
  • ldap.max_links
  • max_input_nesting_level
  • max_input_vars
  • mbstring.regex_retry_limit
  • mbstring.regex_stack_limit
  • mysqli.allow_local_infile
  • mysqli.allow_persistent
  • mysqli.default_port
  • mysqli.max_links
  • mysqli.max_persistent
  • mysqli.rollback_on_cached_plink
  • mysqlnd.log_mask
  • mysqlnd.mempool_default_size
  • mysqlnd.net_read_buffer_size
  • mysqlnd.net_read_timeout
  • oci8.default_prefetch
  • oci8.max_persistent
  • oci8.persistent_timeout
  • oci8.ping_interval
  • oci8.prefetch_lob_size
  • oci8.privileged_connect
  • oci8.statement_cache_size
  • odbc.allow_persistent
  • odbc.check_persistent
  • odbc.max_persistent
  • odbc.max_links
  • odbc.defaultbinmode
  • odbc.default_cursortype
  • odbc.defaultlrl
  • opcache.consistency_checks
  • opcache.file_update_protection
  • opcache.force_restart_timeout
  • opcache.interned_strings_buffer
  • opcache.jit_bisect_limit
  • opcache.jit_blacklist_root_trace
  • opcache.jit_blacklist_side_trace
  • opcache.jit_debug
  • opcache.jit_hot_func
  • opcache.jit_hot_loop
  • opcache.jit_hot_return
  • opcache.jit_hot_side_exit
  • opcache.jit_max_exit_counters
  • opcache.jit_max_loop_unrolls
  • opcache.jit_max_polymorphic_calls
  • opcache.jit_max_recursive_calls
  • opcache.jit_max_recursive_returns
  • opcache.jit_max_root_traces
  • opcache.jit_max_side_traces
  • opcache.log_verbosity_level
  • opcache.max_file_size
  • opcache.opt_debug_level
  • opcache.optimization_level
  • opcache.revalidate_freq
  • output_buffering
  • pcre.backtrack_limit
  • pcre.recursion_limit
  • pgsql.max_links
  • pgsql.max_persistent
  • post_max_size
  • realpath_cache_size
  • realpath_cache_ttl
  • session.cache_expire
  • session.cookie_lifetime
  • session.gc_divisor
  • session.gc_maxlifetime
  • session.gc_probability
  • soap.wsdl_cache_limit
  • soap.wsdl_cache_ttl
  • unserialize_max_depth
  • upload_max_filesize
  • user_ini.cache_ttl
  • xmlrpc_error_number
  • zend.assertions
  • zlib.output_compression_level

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

Core

Windows specific error messages are no longer localized, but instead always displayed in English to better match PHP error messages.

Preliminary and highly experimental support for building on ARM64 has been added.

OCI8

Because building against Oracle Client 10g is no longer supported anyway, the configuration option --with-oci8 has been dropped. The --with-oci8-11g, --with-oci8-12c and --with-oci8-19 configuration options are still supported.

Zip

The Zip extension is upgraded to version 1.21.0, and is now built as shared library (DLL) by default.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 8.0.x to PHP 8.1.x

Table of Contents

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Integer Octal Literal Prefix

Octal integers can now use an explicit 0o/0O prefix in integer literals, similarly to binary and hexadecimal integer literals.

<?php
014; // Non-prefix octal literal
0o14; // Prefixed octal literal
?>

Array Unpacking with String Keys

Added support for array unpacking with strings keys.

<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>

Named Argument After Argument Unpacking

It is now possible to specify named arguments after an argument unpack. e.g. foo(...$args, named: $arg).

full-path Key for File Uploads

File uploads now provide an additional full_path key, which contains the full path (rather than just the basename) of the uploaded file. This is intended for use in conjunction with "upload webkitdirectory".

Enumerations

Support for Enumerations has been added.

Fibers

Support for Fibers has been added.

First Class Callable Syntax

Closures for callables can now be created using the syntax myFunc(...), which is identical to Closure::fromCallable('myFunc').

Note: The ... is part of the syntax, and not an omission.

Intersection Types

Support for intersection types has been added.

Caution

Intersection types cannot be used together with union types

Never type

A new return only type never has been added. This indicates that a function either exit(), throws an exception, or doesn't terminate.

new in Initializers

It is now possible to use new ClassName() expressions as the default value of a parameter, static variable, global constant initializers, and as attribute arguments. Objects can also be passed to define() now.

Readonly properties

Support for readonly has been added.

Final class constants

Added support for the final modifier for class constants. Also, interface constants become overridable by default.

CURL

Added the CURLOPT_DOH_URL option.

Added options for blob certificate when libcurl >= 7.71.0:

  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

Added CURLStringFile, which can be used to post a file from a string rather than a file:

<?php
$file = new CURLStringFile($data, 'filename.txt', 'text/plain');
curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => $file]);
?>

FPM

Added openmetrics status format. It can be used by Prometheus to fetch FPM metrics.

Added new pool option for the dynamic process manager called pm.max_spawn_rate. It allows to start a number of children at a faster rate when dynamic pm is selected. The default value is 32 which was the previous hard coded value.

GD

Avif support is now available through imagecreatefromavif() and imageavif(), if libgd has been built with Avif support.

Hash

The following functions hash(), hash_file(), and hash_init() now support an additional optional options argument, which can be used to pass algorithm specific data.

MurmurHash3

Added support for MurmurHash3 with streaming support. The following variants are implemented:

  • murmur3a, 32-bit hash
  • murmur3c, 128-bit hash for x86
  • murmur3f, 128-bit hash for x64

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("murmur3f", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
A valid seed value is within the range from 0 to the platform defined UINT_MAX, usually 4294967295.

xxHash

Added support for xxHash. The following variants are implemented:

  • xxh32, 32-bit hash
  • xxh64, 64-bit hash
  • xxh3, 64-bit hash
  • xxh128, 128-bit hash

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("xxh3", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Secret usage is supported through passing the secret key in the options array, too:
<?php
$h = hash("xxh3", $data, options: ["secret" => "at least 136 bytes long secret here"]);
echo $h, "\n";
?>
The quality of the custom secret is crucial for the quality of the resulting hash. It is highly recommended for the secret to use the best possible entropy.

MySQLi

New INI directive mysqli.local_infile_directory

The mysqli.local_infile_directory INI directive has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if mysqli.allow_local_infile is not enabled, as all directories are allowed in that case.

Binding parameters in execute

It is now possible to bind parameters by passing them as an array to mysqli_stmt::execute(). All values will be bound as strings. Only list arrays are allowed. This new feature is not available when MySQLi is compiled with libmysqlclient.

<?php
$stmt = $mysqli->prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>

New method mysqli_result::fetch_column()

mysqli_result::fetch_column() has been added to allow fetching a single scalar value from the result set. The new method accepts an optional 0-based column parameter of type int specifying which column to fetch from.

<?php
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>

PDO

The PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY attribute has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if PDO::MYSQL_ATTR_LOCAL_INFILE is not enabled, as all directories are allowed in that case.

PDO_SQLite

SQLite's "file:" DSN syntax is now supported, which allows specifying additional flags. This feature is not available if open_basedir is set.

<?php
new PDO('sqlite:file:path/to/sqlite.db?mode=ro')
?>

POSIX

Added POSIX_RLIMIT_KQUEUES and POSIX_RLIMIT_NPTS. These rlimits are only available on FreeBSD.

Standard

fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

SPL

SplFileObject::fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

cURL

  • CURLStringFile

Intl

  • IntlDatePatternGenerator

Reflection

  • ReflectionFiber

User Contributed Notes

There are no user contributed notes for this page.


New Functions

PHP Core

  • array_is_list()

GD

  • imagecreatefromavif()
  • imageavif()

MySQLi

  • mysqli_result::fetch_column()
  • mysqli_fetch_column()

Process Control

  • pcntl_rfork()

Reflection

  • ReflectionFunctionAbstract::getClosureUsedVariables()

Standard

  • fsync()
  • fdatasync()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20()
  • sodium_crypto_stream_xchacha20_keygen()
  • sodium_crypto_stream_xchacha20_xor()

Ristretto255

Ristretto255 functions are available as of libsodium 1.0.18.

  • sodium_crypto_core_ristretto255_add()
  • sodium_crypto_core_ristretto255_from_hash()
  • sodium_crypto_core_ristretto255_is_valid_point()
  • sodium_crypto_core_ristretto255_random()
  • sodium_crypto_core_ristretto255_scalar_add()
  • sodium_crypto_core_ristretto255_scalar_complement()
  • sodium_crypto_core_ristretto255_scalar_invert()
  • sodium_crypto_core_ristretto255_scalar_mul()
  • sodium_crypto_core_ristretto255_scalar_negate()
  • sodium_crypto_core_ristretto255_scalar_random()
  • sodium_crypto_core_ristretto255_scalar_reduce()
  • sodium_crypto_core_ristretto255_scalar_sub()
  • sodium_crypto_core_ristretto255_sub()
  • sodium_crypto_scalarmult_ristretto255()
  • sodium_crypto_scalarmult_ristretto255_base()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLOPT_DOH_URL
  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

GD

  • IMG_AVIF
  • IMG_WEBP_LOSSLESS

MySQLi

  • MYSQLI_REFRESH_REPLICA

    This constant has been added as a replacement for MYSQLI_REFRESH_SLAVE, in line with an upstream change in MySQL. The old constant is still available for backwards-compatibility reasons, but may be deprecated/removed in the future.

PCNTL

  • PRIO_DARWIN_BG
  • PRIO_DARWIN_THREAD

POSIX

  • POSIX_RLIMIT_KQUEUES
  • POSIX_RLIMIT_NPTS

Sockets

The following socket options are now defined if they are supported:

  • SO_ACCEPTFILTER
  • SO_DONTTRUNC
  • SO_WANTMORE
  • SO_MARK
  • TCP_DEFER_ACCEPT

Sodium

  • SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES

Tokenizer

  • T_READONLY

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

$GLOBALS Access Restrictions

Access to the $GLOBALS array is now subject to a number of restrictions. Read and write access to individual array elements like $GLOBALS['var'] continues to work as-is. Read-only access to the entire $GLOBALS array also continues to be supported. However, write access to the entire $GLOBALS array is no longer supported. For example, array_pop($GLOBALS) will result in an error.

Usage of static Variables in Inherited Methods

When a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method.

<?php
class A {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class B extends A {}
var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(3), previously int(1)
var_dump(B::counter()); // int(4), previously int(2)
?>
This means that static variables in methods now behave the same way as static properties.

Optional parameters specified before required parameters

An optional parameter specified before required parameters is now always treated as required, even when called using named arguments. As of PHP 8.0.0, but prior to PHP 8.1.0, the below emits a deprecation notice on the definition, but runs successfully when called. As of PHP 8.1.0, an error of class ArgumentCountError is thrown, as it would be when called with positional arguments.

<?php
function makeyogurt($container = "bowl", $flavour)
{
return "Making a $container of $flavour yogurt.\n";
}
try
{
echo makeyogurt(flavour: "raspberry");
}
catch (Error $e)
{
echo get_class($e), ' - ', $e->getMessage(), "\n";
}
?>

Output of the above example in PHP 8.0:

Deprecated: Required parameter $flavour follows optional parameter $container
 in example.php on line 3
Making a bowl of raspberry yogurt.

Output of the above example in PHP 8.1:

Deprecated: Optional parameter $container declared before required parameter
 $flavour is implicitly treated as a required parameter in example.php on line 3
ArgumentCountError - makeyogurt(): Argument #1 ($container) not passed

Note that a default value of null can be used before required parameters to specify a nullable type, but the parameter will still be required.

Return Type Compatibility with Internal Classes

Most non-final internal methods now require overriding methods to declare a compatible return type, otherwise a deprecated notice is emitted during inheritance validation. In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a ReturnTypeWillChange attribute can be added to silence the deprecation notice.

New Keywords

readonly is a keyword now. However, it still may be used as function name.

never is now a reserved word, so it cannot be used to name a class, interface or trait, and is also prohibited from being used in namespaces.

Resource to Object Migration

Several resources have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

  • The FileInfo functions now accept and return finfo objects instead of fileinfo resources.

  • The FTP functions now accept and return FTP\Connection objects instead of ftp resources.

  • The IMAP functions now accept and return IMAP\Connection objects instead of imap resources.

  • The LDAP functions now accept and return LDAP\Connection objects instead of ldap link resources.

  • The LDAP functions now accept and return LDAP\Result objects instead of ldap result resources.

  • The LDAP functions now accept and return LDAP\ResultEntry objects instead of ldap result entry resources.

  • The PgSQL functions now accept and return PgSql\Connection objects instead of pgsql link resources.

  • The PgSQL functions now accept and return PgSql\Result objects instead of pgsql result resources.

  • The PgSQL functions now accept and return PgSql\Lob objects instead of pgsql large object resources.

  • The PSpell functions now accept and return PSpell\Dictionary objects instead of pspell resources.

  • The PSpell functions now accept and return PSpell\Config objects instead of pspell config resources.

MySQLi

mysqli_fetch_fields(), and mysqli_fetch_field_direct() will now always return 0 for the max_length. This information can be computed by iterating over the result set, and taking the maximum length. This is what PHP was doing internally previously.

The MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH option no longer has any effect.

The MYSQLI_STORE_RESULT_COPY_DATA option no longer has any effect. Passing any value to the mode parameter of mysqli::store_result() no longer has any effect.

mysqli::connect() now returns true instead of null on success.

The default error handling mode has been changed from "silent" to "exceptions" See the MySQLi reporting mode page for more details on what this entails, and how to explicitly set this attribute. To restore the previous behaviour use: mysqli_report(MYSQLI_REPORT_OFF);

Classes extending mysqli_stmt::execute() are now required to specify the additional optional parameter.

MySQLnd

The mysqlnd.fetch_data_copy INI directive has been removed. This should not result in user-visible behavior changes.

OpenSSL

EC private keys will now be exported in PKCS#8 format rather than traditional format, just like all other keys.

openssl_pkcs7_encrypt() and openssl_cms_encrypt() will now to default using AES-128-CBC rather than RC2-40. The RC2-40 cipher is considered insecure and not enabled by default by OpenSSL 3.

PHP Data Objects

PDO::ATTR_STRINGIFY_FETCHES now stringifies values of type bool to "0" or "1". Previously bools were not stringified.

Calling PDOStatement::bindColumn() with PDO::PARAM_LOB will now constantly bind a stream result when PDO::ATTR_STRINGIFY_FETCHES is not enabled. Previously, the result would either be a stream or a string depending on the used database driver and the time the binding is performed.

MySQL Driver

Integers and floats in result sets will now be returned using native PHP types instead of strings when using emulated prepared statements. This matches the behavior of native prepared statements. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

SQLite Driver

Integers and floats in results sets will now be returned using native PHP types. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

Phar

To comply with the ArrayAccess interface, Phar::offsetUnset() and PharData::offsetUnset() no longer return a bool.

Standard

version_compare() no longer accepts undocumented operator abbreviations.

htmlspecialchars(), htmlentities(), htmlspecialchars_decode(), html_entity_decode(), and get_html_translation_table() now use ENT_QUOTES | ENT_SUBSTITUTE rather than ENT_COMPAT by default. This means that ' is escaped to &#039; while previously nothing was done. Additionally, malformed UTF-8 will be replaced by a Unicode substitution character, instead of resulting in an empty string.

debug_zval_dump() now prints the refcount of a reference wrappers with their refcount, instead of only prepending & to the value. This more accurately models reference representation since PHP 7.0.

debug_zval_dump() now prints interned instead of a dummy refcount for interned strings and immutable arrays.

Standard PHP Library (SPL)

SplFixedArray, will now be JSON encoded like an array

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Implementing Serializable without __serialize() and __unserialize()

Either only the new methods should be implemented, if no support for PHP prior to version 7.4 is provided, or both should be implemented.

Passing null to non-nullable parameters of built-in functions

Scalar types for built-in functions are nullable by default. This behaviour is deprecated to align with the behaviour of user-defined functions, where scalar types need to be marked as nullable explicitly.

<?php
var_dump(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
// is deprecated
?>

Implicit incompatible float to int conversions

The implicit conversion of float to int which leads to a loss in precision is now deprecated. This affects array keys, int type declarations in coercive mode, and operators working on ints.

<?php
$a = [];
$a[15.5]; // deprecated, as key value loses the 0.5 component
$a[15.0]; // ok, as 15.0 == 15
?>

Calling a static element on a trait

Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

Returning a non-array from __sleep()

Returning a value which is not an array from __sleep() now generates a diagnostic.

Returning by reference from a void function

<?php
function &test(): void {}
?>
Such a function is contradictory, and already emits the following E_NOTICE when called: Only variable references should be returned by reference.

Autovivification from false

Autovivification is the process of creating a new array when appending to a value. Autovivification is prohibited from scalar values, false however was an exception. This is now deprecated.

<?php
$arr = false;
$arr[] = 2; // deprecated
?>

Note:

Autovivification from null and undefined values is still allowed:

<?php
// From undefined
$arr[] = 'some value';
$arr['doesNotExist'][] = 2;
// From null
$arr = null;
$arr[] = 2;
?>

ctype

Verifying non-string arguments

Passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to chr() should be made. All ctype_*() functions are affected.

Date

date_sunrise() and date_sunset() have been deprecated in favor of date_sun_info().

strptime() has been deprecated.
Use date_parse_from_format() instead (for locale-independent parsing),
or IntlDateFormatter::parse() (for locale-dependent parsing).

strftime() and gmstrftime() have been deprecated.
Use date() instead (for locale-independent formatting),
or IntlDateFormatter::format() (for locale-dependent formatting).

Filter

The FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED filters are deprecated.

The filter.default INI directive is deprecated.

GD

The num_points of imagepolygon(), imageopenpolygon() and imagefilledpolygon() has been deprecated.

Hash

The mhash(),
mhash_keygen_s2k(),
mhash_count(),
mhash_get_block_size(),
and mhash_get_hash_name() have been deprecated.
Use the hash_*() functions instead.

IMAP

The NIL constant has been deprecated. Use 0 instead.

Intl

Calling IntlCalendar::roll() with a bool argument is deprecated. Use 1 and -1 instead of true and false respectively.

Multibyte String

Calling mb_check_encoding() without any arguments is deprecated.

MySQLi

The mysqli_driver::$driver_version property has been deprecated. It was meaningless and outdated, use PHP_VERSION_ID instead.

Calling mysqli::get_client_info() or mysqli_get_client_info() with the mysqli argument has been deprecated. Call mysqli_get_client_info() without any arguments to obtain the version information of the client library.

The mysqli::init() method has been deprecated.
Replace calls to parent::init() with
parent::__construct().

OCI8

The oci8.old_oci_close_semantics INI directive is deprecated.

ODBC

odbc_result_all() has been deprecated.

PDO

The PDO::FETCH_SERIALIZE fetch mode has been deprecated.

PgSQL

Not passing the connection argument to all pgsql_*() functions has been deprecated.

SOAP

The ssl_method option of SoapClient::__construct() has been deprecated in favor of SSL stream context options.

Standard

Calling key(), current(), next(), prev(), reset(), or end() on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead.

The auto_detect_line_endings INI directive is deprecated. If necessary, handle "\r" line breaks manually instead.

The FILE_BINARY and FILE_TEXT constants have been deprecated. They never had any effect.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Changes in SAPI Modules

CLI

Using -a without the readline extension will now result in an error. Previously, -a without readline had the same behavior as calling php without any arguments, apart from printing an additional "Interactive mode enabled" message. This mode was not interactive.

PHPDBG

Remote functionality from phpdbg has been removed.

Changed Functions

Core

The order of properties used in foreach, var_dump(), serialize(), object comparison, etc. was changed. Properties are now ordered naturally according to their declaration and inheritance. Properties declared in a base class are going to be before the child properties.

This order is consistent with internal layout of properties in zend_object structure and repeats the order in default_properties_table[] and properties_info_table[]. The old order was not documented and was caused by class inheritance implementation details.

Filter

The FILTER_FLAG_ALLOW_OCTAL flag of the FILTER_VALIDATE_INT filter now accept octal string with the leading octal prefix ("0o"/"0O").

GMP

All GMP functions now accept octal string with the leading octal prefix ("0o"/"0O").

PDO ODBC

PDO::getAttribute() with
PDO::ATTR_SERVER_INFO and
PDO::ATTR_SERVER_VERSION
now return values instead of throwing PDOException.

Reflection

ReflectionProperty::setAccessible() and ReflectionMethod::setAccessible() no longer have an effect. Properties and methods are now always considered accessible via Reflection.

Standard

syslog() is now binary safe.

Other Changes to Extensions

GD

imagewebp() can now do lossless WebP encoding by passing IMG_WEBP_LOSSLESS as the quality.

This constant is only defined, if the used libgd supports lossless WebP encoding.

MySQLi

mysqli_stmt::next_result() and mysqli::fetch_all() are now available when linking against libmysqlclient.

OpenSSL

  • The OpenSSL extension now requires at least OpenSSL version 1.0.2.

  • OpenSSL 3.0 is now supported. Be aware that many ciphers are no longer enabled by default (part of the legacy provider), and that parameter validation (e.g. minimum key sizes) is stricter now.

Phar

  • SHA256 is now used by default for signatures.

  • Added support for OpenSSL_SHA256 and OpenSSL_SHA512 signatures.

SNMP

  • Added support for SHA256 and SHA512 for the security protocol.

Standard

--with-password-argon2 now uses pkg-config to detect libargon2. As such, an alternative libargon2 location should now be specified using PKG_CONFIG_PATH.

Changes to INI File Handling

  • The log_errors_max_len INI directive has been removed. It no longer had an effect since PHP 8.0.0.

  • A leading dollar in a quoted string can now be escaped: "\${" will now be interpreted as a string with contents ${.

  • Backslashes in double quoted strings are now more consistently treated as escape characters. Previously, "foo\\" followed by something other than a newline was not considered as a terminated string. It is now interpreted as a string with contents foo\. However, as an exception, the string "foo\" followed by a newline will continue to be treated as a valid string with contents foo\ rather than an unterminated string. This exception exists to support naive uses of Windows file paths such as "C:\foo\".

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 7.4.x to PHP 8.0.x

Table of Contents

  • New Features
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes

This new major version brings with it a number of new features and some incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x, 7.1.x, 7.2.x, 7.3.x. 7.4.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Named Arguments

Support for Named Arguments has been added.

Attributes

Support for Attributes has been added.

Constructor Property Promotion

Support for constructor property promotion (declaring properties in the constructor signature) has been added.

Union Types

Support for union types has been added.

Match Expression

Support for match expressions has been added.

Nullsafe Operator

Support for the nullsafe operator (?->) has been added.

Other new Features

  • The WeakMap class has been added.

  • The ValueError class has been added.

  • Any number of function parameters may now be replaced by a variadic argument, as long as the types are compatible. For example, the following code is now allowed:

    <?php
    class A {
    public function     method(int $many, string $parameters, $here) {}
    }
    class     B extends A {
    public function     method(...$everything) {}
    }
    ?>

  • static (as in "late static binding") can now be used as a return type:

    <?php
    class Test {
    public function     create(): static {
    return new static();
    }
    }
    ?>

  • It is now possible to fetch the class name of an object using $object::class. The result is the same as get_class($object).

  • new and instanceof can now be used with arbitrary expressions, using new (expression)(...$args) and $obj instanceof (expression).

  • Some consistency fixes to variable syntax have been applied, for example writing Foo::BAR::$baz is now allowed.

  • Added Stringable interface, which is automatically implemented if a class defines a __toString() method.

  • Traits can now define abstract private methods. Such methods must be implemented by the class using the trait.

  • throw can now be used as an expression. That allows usages like:

    <?php
    $fn     = fn() => throw new Exception('Exception in arrow function');
    $user = $session->user ?? throw new Exception('Must have user');

  • An optional trailing comma is now allowed in parameter lists.

    <?php
    function functionWithLongSignature(
    Type1 $parameter1,
    Type2 $parameter2, // <-- This comma is now allowed.
    ) {
    }

  • It is now possible to write catch (Exception) to catch an exception without storing it in a variable.

  • Support for mixed type has been added.

  • Private methods declared on a parent class no longer enforce any inheritance rules on the methods of a child class (with the exception of final private constructors). The following example illustrates which restrictions have been removed:

    <?php
    class ParentClass {
    private function     method1() {}
    private function     method2() {}
    private static function     method3() {}
    // Throws a warning, as "final" no longer has an effect:
    private final function method4() {}
    }
    class     ChildClass extends ParentClass {
    // All of the following are now allowed, even though the modifiers aren't
    // the same as for the private methods in the parent class.
    public abstract function method1() {}
    public static function     method2() {}
    public function     method3() {}
    public function     method4() {}
    }
    ?>

  • get_resource_id() has been added, which returns the same value as (int) $resource. It provides the same functionality under a clearer API.

  • The InternalIterator has been added.

Date and Time

  • DateTime::createFromInterface() and DateTimeImmutable::createFromInterface() have been added.

  • The DateTime format specifier p has been added, which is the same as P but returns Z rather than +00:00 for UTC.

DOM

DOMParentNode and DOMChildNode with new traversal and manipulation APIs have been added.

Filter

FILTER_VALIDATE_BOOL has been added as an alias for FILTER_VALIDATE_BOOLEAN. The new name is preferred, as it uses the canonical type name.

Enchant

enchant_dict_add(), enchant_dict_is_added(), and LIBENCHANT_VERSION have been added.

FPM

Added a new option pm.status_listen that allows getting the status from different endpoint (e.g. port or UDS file) which is useful for getting the status when all children are busy with serving long running requests.

Hash

HashContext objects can now be serialized.

Internationalization Functions

The IntlDateFormatter::RELATIVE_FULL,
IntlDateFormatter::RELATIVE_LONG,
IntlDateFormatter::RELATIVE_MEDIUM, and
IntlDateFormatter::RELATIVE_SHORT
constants have been added.

LDAP

ldap_count_references() has been added, which returns the number of reference messages in a search result.

OPcache

If the opcache.record_warnings ini setting is enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.

OpenSSL

Added Cryptographic Message Syntax (CMS) (» RFC 5652) support composed of functions for encryption, decryption, signing, verifying and reading. The API is similar to the API for PKCS #7 functions with an addition of new encoding constants: OPENSSL_ENCODING_DER, OPENSSL_ENCODING_SMIME and OPENSSL_ENCODING_PEM:

  • openssl_cms_encrypt() encrypts the message in the file with the certificates and outputs the result to the supplied file.
  • openssl_cms_decrypt() that decrypts the S/MIME message in the file and outputs the results to the supplied file.
  • openssl_cms_read() that exports the CMS file to an array of PEM certificates.
  • openssl_cms_sign() that signs the MIME message in the file with a cert and key and output the result to the supplied file.
  • openssl_cms_verify() that verifies that the data block is intact, the signer is who they say they are, and returns the certs of the signers.

Regular Expressions (Perl-Compatible)

preg_last_error_msg() has been added, which returns a human-readable message for the last PCRE error. It complements preg_last_error(), which returns an integer enum value instead.

Reflection

  • The following methods can now return information about default values of parameters of internal functions:

    • ReflectionParameter::isDefaultValueAvailable()
    • ReflectionParameter::getDefaultValue()
    • ReflectionParameter::isDefaultValueConstant()
    • ReflectionParameter::getDefaultValueConstantName()

SQLite3

SQLite3::setAuthorizer() and respective class constants have been added to set a userland callback that will be used to authorize or not an action on the database.

Standard Library

  • str_contains(), str_starts_with() and str_ends_with() have been added, which check whether haystack contains, starts with or ends with needle, respectively.

  • fdiv() has been added, which performs a floating-point division under IEEE 754 semantics. Division by zero is considered well-defined and will return one of Inf, -Inf or NaN.

  • get_debug_type() has been added, which returns a type useful for error messages. Unlike gettype(), it uses canonical type names, returns class names for objects, and indicates the resource type for resources.

  • printf() and friends now support the %h and %H format specifiers. These are the same as %g and %G, but always use "." as the decimal separator, rather than determining it through the LC_NUMERIC locale.

  • printf() and friends now support using "*" as width or precision, in which case the width/precision is passed as an argument to printf. This also allows using precision -1 with %g, %G, %h and %H. For example, the following code can be used to reproduce PHP's default floating point formatting:

    <?php
    printf    ("%.*H", (int) ini_get("precision"), $float);
    printf("%.*H", (int) ini_get("serialize_precision"), $float);
    ?>

  • proc_open() now supports pseudo-terminal (PTY) descriptors. The following attaches stdin, stdout and stderr to the same PTY:

    <?php
    $proc     = proc_open($command, [['pty'], ['pty'], ['pty']], $pipes);
    ?>

  • proc_open() now supports socket pair descriptors. The following attaches a distinct socket pair to stdin, stdout and stderr:

    <?php
    $proc     = proc_open($command, [['socket'], ['socket'], ['socket']], $pipes);
    ?>

    Unlike pipes, sockets do not suffer from blocking I/O issues on Windows. However, not all programs may work correctly with stdio sockets.

  • Sorting functions are now stable, which means that equal-comparing elements will retain their original order.

  • array_diff(), array_intersect() and their variations can now be used with a single array as argument. This means that usages like the following are now possible:

    <?php
    // OK even if $excludes is empty:
    array_diff($array, ...$excludes);
    // OK even if $arrays only contains a single array:
    array_intersect(...$arrays);
    ?>

  • The flag parameter of ob_implicit_flush() was changed to accept a bool rather than an int.

Tokenizer

PhpToken adds an object-based interface to the tokenizer. It provides a more uniform and ergonomic representation, while being more memory efficient and faster.

Zip

  • The Zip extension has been updated to version 1.19.1.

  • New ZipArchive::setMtimeName() and ZipArchive::setMtimeIndex() to set the modification time of an entry.

  • New ZipArchive::registerProgressCallback() to provide updates during archive close.

  • New ZipArchive::registerCancelCallback() to allow cancellation during archive close.

  • New ZipArchive::replaceFile() to replace an entry content.

  • New ZipArchive::isCompressionMethodSupported() to check optional compression features.

  • New ZipArchive::isEncryptionMethodSupported() to check optional encryption features.

  • The ZipArchive::lastId property to get the index value of the last added entry has been added.

  • Errors can now be checked after an archive has been closed using the
ZipArchive::status and
ZipArchive::statusSys properties, or the
ZipArchive::getStatusString() method.

  • The 'remove_path' option of ZipArchive::addGlob() and ZipArchive::addPattern() is now treated as an arbitrary string prefix (for consistency with the 'add_path' option), whereas formerly it was treated as a directory name.

  • Optional compression / encryption features are now listed in phpinfo.

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

String to Number Comparison

Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings. Comparisons between numbers and numeric strings continue to work as before. Notably, this means that 0 == "not-a-number" is considered false now.

Comparison | Before | After
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Other incompatible Changes

  • match is now a reserved keyword.

  • mixed is now a reserved word, so it cannot be used to name a class, interface or trait, and is also prohibited from being used in namespaces.

  • Assertion failures now throw by default. If the old behavior is desired, assert.exception=0 can be set in the INI settings.

  • Methods with the same name as the class are no longer interpreted as constructors. The __construct() method should be used instead.

  • The ability to call non-static methods statically has been removed. Thus is_callable() will fail when checking for a non-static method with a classname (must check with an object instance).

  • The (real) and (unset) casts have been removed.

  • The track_errors ini directive has been removed. This means that php_errormsg is no longer available. The error_get_last() function may be used instead.

  • The ability to define case-insensitive constants has been removed. The third argument to define() may no longer be true.

  • The ability to specify an autoloader using an __autoload() function has been removed. spl_autoload_register() should be used instead.

  • The errcontext argument will no longer be passed to custom error handlers set with set_error_handler().

  • create_function() has been removed. Anonymous functions may be used instead.

  • each() has been removed. foreach or ArrayIterator should be used instead.

  • The ability to unbind this from closures that were created from a method, using Closure::fromCallable() or ReflectionMethod::getClosure(), has been removed.

  • The ability to unbind this from proper closures that contain uses of this has also been removed.

  • The ability to use array_key_exists() with objects has been removed. isset() or property_exists() may be used instead.

  • The behavior of array_key_exists() regarding the type of the key parameter has been made consistent with isset() and normal array access. All key types now use the usual coercions and array/object keys throw a TypeError.

  • Any array that has a number n as its first numeric key will use n+1 for its next implicit key, even if n is negative.

  • The default error_reporting level is now E_ALL. Previously it excluded E_NOTICE and E_DEPRECATED.

  • display_startup_errors is now enabled by default.

  • Using parent inside a class that has no parent will now result in a fatal compile-time error.

  • The @ operator will no longer silence fatal errors (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Error handlers that expect error_reporting to be 0 when @ is used, should be adjusted to use a mask check instead:

    <?php
    // Replace
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (    error_reporting() == 0) {
    return     false;
    }
    // ...
    }

    // With
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (!(    error_reporting() & $err_no)) {
    return     false;
    }
    // ...
    }
    ?>

    Additionally, care should be taken that error messages are not displayed in production environments, which can result in information leaks. Please ensure that display_errors=Off is used in conjunction with error logging.

  • #[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.

  • Inheritance errors due to incompatible method signatures (LSP violations) will now always generate a fatal error. Previously a warning was generated in some cases.

  • The precedence of the concatenation operator has changed relative to bitshifts and addition as well as subtraction.

    <?php
    echo "Sum: " . $a + $b;
    // was previously interpreted as:
    echo ("Sum: " . $a) + $b;
    // is now interpreted as:
    echo "Sum:" . ($a + $b);
    ?>

  • Arguments with a default value that resolves to null at runtime will no longer implicitly mark the argument type as nullable. Either an explicit nullable type, or an explicit null default value has to be used instead.

    <?php
    // Replace
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // With
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // Or
    function test(int $arg = null) {}
    ?>

  • A number of warnings have been converted into Error exceptions:

    • Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
    • Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
    • Attempting to use an invalid type (array or object) as an array key or string offset.
    • Attempting to write to an array index of a scalar value.
    • Attempting to unpack a non-array/Traversable.
    • Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings.
    • Passing the wrong number of arguments to a non-variadic built-in function will throw an ArgumentCountError.

    A number of notices have been converted into warnings:

    • Attempting to read an undefined variable.
    • Attempting to read an undefined property.
    • Attempting to read an undefined array key.
    • Attempting to read a property of a non-object.
    • Attempting to access an array index of a non-array.
    • Attempting to convert an array to string.
    • Attempting to use a resource as an array key.
    • Attempting to use null, a boolean, or a float as a string offset.
    • Attempting to read an out-of-bounds string offset.
    • Attempting to assign an empty string to a string offset.

  • Attempting to assign multiple bytes to a string offset will now emit a warning.

  • Unexpected characters in source files (such as NUL bytes outside of strings) will now result in a ParseError exception instead of a compile warning.

  • Uncaught exceptions now go through "clean shutdown", which means that destructors will be called after an uncaught exception.

  • The compile time fatal error "Only variables can be passed by reference" has been delayed until runtime, and converted into an "Argument cannot be passed by reference" Error exception.

  • Some "Only variables should be passed by reference" notices have been converted to "Argument cannot be passed by reference" exception.

  • The generated name for anonymous classes has changed. It will now include the name of the first parent or interface:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    The name shown above is still followed by a NUL byte and a unique suffix.

  • Non-absolute trait method references in trait alias adaptations are now required to be unambiguous:

    <?php
    class X {
    use     T1, T2 {
    func as otherFunc;
    }
    function     func() {}
    }
    ?>

    If both T1::func() and T2::func() exist, this code was previously silently accepted, and func was assumed to refer to T1::func. Now it will generate a fatal error instead, and either T1::func or T2::func needs to be written explicitly.

  • The signature of abstract methods defined in traits is now checked against the implementing class method:

    <?php
    trait MyTrait {
    abstract private function     neededByTrait(): string;
    }

    class     MyClass {
    use     MyTrait;

    // Error, because of return type mismatch.
    private function neededByTrait(): int { return 42; }
    }
    ?>

  • Disabled functions are now treated exactly like non-existent functions. Calling a disabled function will report it as unknown, and redefining a disabled function is now possible.

  • data:// stream wrappers are no longer writable, which matches the documented behavior.

  • The arithmetic and bitwise operators +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- will now consistently throw a TypeError when one of the operands is an array, resource or non-overloaded object. The only exception to this is the array + array merge operation, which remains supported.

  • Float to string casting will now always behave locale-independently.

    <?php
    setlocale    (LC_ALL, "de_DE");
    $f = 3.14;
    echo     $f, "\n";
    // Previously: 3,14
    // Now: 3.14
    ?>

    See printf(), number_format() and NumberFormatter() for ways to customize number formatting.

  • Support for deprecated curly braces for offset access has been removed.

    <?php
    // Instead of:
    $array{0};
    $array{"key"};
    // Write:
    $array[0];
    $array["key"];
    ?>

  • Applying the final modifier on a private method will now produce a warning unless that method is the constructor.

  • If an object constructor exit()s, the object destructor will no longer be called. This matches the behavior when the constructor throws.

  • Namespaced names can no longer contain whitespace: While Foo\Bar will be recognized as a namespaced name, Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code: new\x is now the same as constant('new\x'), not new \x().

  • Nested ternaries now require explicit parentheses.

  • debug_backtrace() and Exception::getTrace() will no longer provide references to arguments. It will not be possible to change function arguments through the backtrace.

  • Numeric string handling has been altered to be more intuitive and less error-prone. Trailing whitespace is now allowed in numeric strings for consistency with how leading whitespace is treated. This mostly affects:

    • The is_numeric() function
    • String-to-string comparisons
    • Type declarations
    • Increment and decrement operations

    The concept of a "leading-numeric string" has been mostly dropped; the cases where this remains exist in order to ease migration. Strings which emitted an E_NOTICE "A non well-formed numeric value encountered" will now emit an E_WARNING "A non-numeric value encountered" and all strings which emitted an E_WARNING "A non-numeric value encountered" will now throw a TypeError. This mostly affects:

    • Arithmetic operations
    • Bitwise operations

    This E_WARNING to TypeError change also affects the E_WARNING "Illegal string offset 'string'" for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.

  • Magic Methods will now have their arguments and return types checked if they have them declared. The signatures should match the following list:

    • __call(string $name, array $arguments): mixed
    • __callStatic(string $name, array $arguments): mixed
    • __clone(): void
    • __debugInfo(): ?array
    • __get(string $name): mixed
    • __invoke(mixed $arguments): mixed
    • __isset(string $name): bool
    • __serialize(): array
    • __set(string $name, mixed $value): void
    • __set_state(array $properties): object
    • __sleep(): array
    • __unserialize(array $data): void
    • __unset(string $name): void
    • __wakeup(): void

  • call_user_func_array() array keys will now be interpreted as parameter names, instead of being silently ignored.

  • Declaring a function called assert() inside a namespace is no longer allowed, and issues E_COMPILE_ERROR. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Resource to Object Migration

Several resources have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

  • curl_init() will now return a CurlHandle object rather than a resource. The curl_close() function no longer has an effect, instead the CurlHandle instance is automatically destroyed if it is no longer referenced.

  • curl_multi_init() will now return a CurlMultiHandle object rather than a resource. The curl_multi_close() function no longer has an effect, instead the CurlMultiHandle instance is automatically destroyed if it is no longer referenced.

  • curl_share_init() will now return a CurlShareHandle object rather than a resource. The curl_share_close() function no longer has an effect, instead the CurlShareHandle instance is automatically destroyed if it is no longer referenced.

  • enchant_broker_init() will now return an EnchantBroker object rather than a resource.

  • enchant_broker_request_dict() and enchant_broker_request_pwl_dict() will now return an EnchantDictionary object rather than a resource.

  • The GD extension now uses GdImage objects as the underlying data structure for images, rather than resources. The imagedestroy() function no longer has an effect; instead the GdImage instance is automatically destroyed if it is no longer referenced.

  • openssl_x509_read() and openssl_csr_sign() will now return an OpenSSLCertificate object rather than a resource. The openssl_x509_free() function is deprecated and no longer has an effect, instead the OpenSSLCertificate instance is automatically destroyed if it is no longer referenced.

  • openssl_csr_new() will now return an OpenSSLCertificateSigningRequest object rather than a resource.

  • openssl_pkey_new() will now return an OpenSSLAsymmetricKey object rather than a resource. The openssl_pkey_free() function is deprecated and no longer has an effect, instead the OpenSSLAsymmetricKey instance is automatically destroyed if it is no longer referenced.

  • shmop_open() will now return a Shmop object rather than a resource. The shmop_close() function no longer has an effect, and is deprecated; instead the Shmop instance is automatically destroyed if it is no longer referenced.

  • socket_create(), socket_create_listen(), socket_accept(), socket_import_stream(), socket_addrinfo_connect(), socket_addrinfo_bind(), and socket_wsaprotocol_info_import() will now return a Socket object rather than a resource. socket_addrinfo_lookup() will now return an array of AddressInfo objects rather than resources.

  • msg_get_queue() will now return an SysvMessageQueue object rather than a resource.

  • sem_get() will now return an SysvSemaphore object rather than a resource.

  • shm_attach() will now return an SysvSharedMemory object rather than a resource.

  • xml_parser_create() and xml_parser_create_ns() will now return an XMLParser object rather than a resource. The xml_parser_free() function no longer has an effect, instead the XMLParser instance is automatically destroyed if it is no longer referenced.

  • The XMLWriter functions now accept and return, respectively, XMLWriter objects instead of resources.

  • inflate_init() will now return an InflateContext object rather than a resource.

  • deflate_init() will now return a DeflateContext object rather than a resource.

COM and .Net (Windows)

The ability to import case-insensitive constants from type libraries has been removed. The second argument to com_load_typelib() may no longer be false; com.autoregister_casesensitive may no longer be disabled; case-insensitive markers in com.typelib_file are ignored.

CURL

CURLOPT_POSTFIELDS no longer accepts objects as arrays. To interpret an object as an array, perform an explicit (array) cast. The same applies to other options accepting arrays as well.

Date and Time

mktime() and gmmktime() now require at least one argument. time() can be used to get the current timestamp.

DOM

Unimplemented classes from the DOM extension that had no behavior and contained test data have been removed. These classes have also been removed in the latest version of the DOM standard:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo
  • DOMStringExtend

Unimplemented methods from the DOM extension that had no behavior have been removed:

  • DOMNamedNodeMap::setNamedItem()
  • DOMNamedNodeMap::removeNamedItem()
  • DOMNamedNodeMap::setNamedItemNS()
  • DOMNamedNodeMap::removeNamedItemNS()
  • DOMText::replaceWholeText()
  • DOMNode::compareDocumentPosition()
  • DOMNode::isEqualNode()
  • DOMNode::getFeature()
  • DOMNode::setUserData()
  • DOMNode::getUserData()
  • DOMDocument::renameNode()

Enchant

  • enchant_broker_list_dicts(), enchant_broker_describe() and enchant_dict_suggest() will now return an empty array instead of null.

Exif

read_exif_data() has been removed; exif_read_data() should be used instead.

Filter

  • The FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags for the FILTER_VALIDATE_URL filter have been removed. The scheme and host are (and have been) always required.

  • The INPUT_REQUEST and INPUT_SESSION source for filter_input() etc. have been removed. These were never implemented and their use always generated a warning.

GD

  • The deprecated function image2wbmp() has been removed.

  • The deprecated functions png2wbmp() and jpeg2wbmp() have been removed.

  • The default mode parameter of imagecropauto() no longer accepts -1. IMG_CROP_DEFAULT should be used instead.

  • On Windows, php_gd2.dll has been renamed to php_gd.dll.

GMP

gmp_random() has been removed. One of gmp_random_range() or gmp_random_bits() should be used instead.

Iconv

iconv implementations which do not properly set errno in case of errors are no longer supported.

IMAP

  • The unused default_host argument of imap_headerinfo() has been removed.

  • The imap_header() function which is an alias of imap_headerinfo() has been removed.

Internationalization Functions

  • The deprecated constant INTL_IDNA_VARIANT_2003 has been removed.

  • The deprecated Normalizer::NONE constant has been removed.

LDAP

  • The deprecated functions ldap_sort(),
ldap_control_paged_result() and
ldap_control_paged_result_response() have been removed.

  • The interface of ldap_set_rebind_proc() has changed; the callback parameter does not accept empty strings anymore; null should be used instead.

MBString

  • The mbstring.func_overload directive has been removed. The related MB_OVERLOAD_MAIL, MB_OVERLOAD_STRING, and MB_OVERLOAD_REGEX constants have also been removed. Finally, the "func_overload" and "func_overload_list" entries in mb_get_info() have been removed.

  • mb_parse_str() can no longer be used without specifying a result array.

  • A number of deprecated mbregex aliases have been removed. See the following list for which functions should be used instead:

    • mbregex_encoding() → mb_regex_encoding()
    • mbereg() → mb_ereg()
    • mberegi() → mb_eregi()
    • mbereg_replace() → mb_ereg_replace()
    • mberegi_replace() → mb_eregi_replace()
    • mbsplit() → mb_split()
    • mbereg_match() → mb_ereg_match()
    • mbereg_search() → mb_ereg_search()
    • mbereg_search_pos() → mb_ereg_search_pos()
    • mbereg_search_regs() → mb_ereg_search_regs()
    • mbereg_search_init() → mb_ereg_search_init()
    • mbereg_search_getregs() → mb_ereg_search_getregs()
    • mbereg_search_getpos() → mb_ereg_search_getpos()
    • mbereg_search_setpos() → mb_ereg_search_setpos()

  • The e modifier for mb_ereg_replace() has been removed. mb_ereg_replace_callback() should be used instead.

  • A non-string pattern argument to mb_ereg_replace() will now be interpreted as a string instead of an ASCII codepoint. The previous behavior may be restored with an explicit call to chr().

  • The needle argument for mb_strpos(),
mb_strrpos(), mb_stripos(),
mb_strripos(), mb_strstr(),
mb_stristr(), mb_strrchr() and
mb_strrichr() can now be empty.

  • The is_hex parameter, which was not used internally, has been removed from mb_decode_numericentity().

  • The legacy behavior of passing the encoding as the third argument instead of an offset for the mb_strrpos() function has been removed; an explicit 0 offset with the encoding should be provided as the fourth argument instead.

  • The ISO_8859-* character encoding aliases have been replaced by ISO8859-* aliases for better interoperability with the iconv extension. The mbregex ISO 8859 aliases with underscores (ISO_8859_* and ISO8859_*) have also been removed.

  • mb_ereg() and mb_eregi() will now return boolean true on a successful match. Previously they returned integer 1 if matches was not passed, or max(1, strlen($matches[0])) if matches was passed.

OCI8

  • The OCI-Lob class is now called OCILob, and the OCI-Collection class is now called OCICollection for name compliance enforced by PHP 8 arginfo type annotation tooling.

  • Several alias functions have been marked as deprecated.

  • oci_internal_debug() and its alias ociinternaldebug() have been removed.

ODBC

  • odbc_connect() no longer reuses connections.

  • The unused flags parameter of odbc_exec() has been removed.

OpenSSL

  • openssl_seal() and openssl_open() now require method to be passed, as the previous default of "RC4" is considered insecure.

Regular Expressions (Perl-Compatible)

When passing invalid escape sequences they are no longer interpreted as literals. This behavior previously required the X modifier – which is now ignored.

PHP Data Objects

  • The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.

  • The signatures of some PDO methods have changed:

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO ODBC

The php.ini directive pdo_odbc.db2_instance_name has been removed.

PDO MySQL

PDO::inTransaction() now reports the actual transaction state of the connection, rather than an approximation maintained by PDO. If a query that is subject to "implicit commit" is executed, PDO::inTransaction() will subsequently return false, as a transaction is no longer active.

PostgreSQL

  • The deprecated pg_connect() syntax using multiple parameters instead of a connection string is no longer supported.

  • The deprecated pg_lo_import() and pg_lo_export() signature that passes the connection as the last argument is no longer supported. The connection should be passed as first argument instead.

  • pg_fetch_all() will now return an empty array instead of false for result sets with zero rows.

Phar

Metadata associated with a phar will no longer be automatically unserialized, to fix potential security vulnerabilities due to object instantiation, autoloading, etc.

Reflection

  • The method signatures

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    have been changed to:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Code that must be compatible with both PHP 7 and PHP 8 can use the following signatures to be compatible with both versions:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • The ReflectionType::__toString() method will now return a complete debug representation of the type, and is no longer deprecated. In particular the result will include a nullability indicator for nullable types. The format of the return value is not stable and may change between PHP versions.

  • Reflection export() methods have been removed. Instead reflection objects can be cast to string.

  • ReflectionMethod::isConstructor() and
ReflectionMethod::isDestructor() now also return true for
__construct() and
__destruct() methods of interfaces.
Previously, this would only be true for methods of classes and traits.

  • ReflectionType::isBuiltin() method has been moved to ReflectionNamedType. ReflectionUnionType does not have it.

Sockets

  • The deprecated AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() have been removed.

Standard PHP Library (SPL)

  • SplFileObject::fgetss() has been removed.

  • SplFileObject::seek() now always seeks to the beginning of the line. Previously, positions >=1 sought to the beginning of the next line.

  • SplHeap::compare() now specifies a method signature. Inheriting classes implementing this method will now have to use a compatible method signature.

  • SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() and SplQueue::enqueue() now return void instead of true.

  • spl_autoload_register() will now always throw a TypeError on invalid arguments, therefore the second argument do_throw is ignored and a notice will be emitted if it is set to false.

  • SplFixedArray is now an IteratorAggregate and not an Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), and SplFixedArray::valid() have been removed. In their place, SplFixedArray::getIterator() has been added. Any code which uses explicit iteration over SplFixedArray must now obtain an Iterator through SplFixedArray::getIterator(). This means that SplFixedArray is now safe to use in nested loops.

Standard Library

  • assert() will no longer evaluate string arguments, instead they will be treated like any other argument. assert($a == $b) should be used instead of assert('$a == $b'). The assert.quiet_eval ini directive and the ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.

  • parse_str() can no longer be used without specifying a result array.

  • The string.strip_tags filter has been removed.

  • The needle argument of strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), and stristr() will now always be interpreted as a string. Previously non-string needles were interpreted as an ASCII code point. An explicit call to chr() can be used to restore the previous behavior.

  • The needle argument for strpos(),
strrpos(), stripos(), strripos(),
strstr(), stristr() and strrchr() can
now be empty.

  • The length argument for substr(), substr_count(), substr_compare(), and iconv_substr() can now be null. null values will behave as if no length argument was provided and will therefore return the remainder of the string instead of an empty string.

  • The length argument for array_splice() can now be null. null values will behave identically to omitting the argument, thus removing everything from the offset to the end of the array.

  • The args argument of vsprintf(), vfprintf(), and vprintf() must now be an array. Previously any type was accepted.

  • The 'salt' option of password_hash() is no longer supported. If the 'salt' option is used a warning is generated, the provided salt is ignored, and a generated salt is used instead.

  • The quotemeta() function will now return an empty string if an empty string was passed. Previously false was returned.

  • The following functions have been removed:

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • FILTER_SANITIZE_MAGIC_QUOTES has been removed.

  • Calling implode() with parameters in a reverse order ($pieces, $glue) is no longer supported.

  • parse_url() will now distinguish absent and empty queries and fragments:

    • http://example.com/foo → query = null, fragment = null
    • http://example.com/foo? → query = "", fragment = null
    • http://example.com/foo# → query = null, fragment = ""
    • http://example.com/foo?# → query = "", fragment = ""
    Previously all cases resulted in query and fragment being null.

  • var_dump() and debug_zval_dump() will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.

  • If the array returned by __sleep() contains non-existing properties, these are now silently ignored. Previously, such properties would have been serialized as if they had the value null.

  • The default locale on startup is now always "C". No locales are inherited from the environment by default. Previously, LC_ALL was set to "C", while LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit setlocale() call. An explicit setlocale() call is now always required if a locale component should be changed from the default.

  • The deprecated DES fallback in crypt() has been removed. If an unknown salt format is passed to crypt(), the function will fail with *0 instead of falling back to a weak DES hash now.

  • Specifying out of range rounds for SHA256/SHA512 crypt() will now fail with *0 instead of clamping to the closest limit. This matches glibc behavior.

  • The result of sorting functions may have changed, if the array contains elements that compare as equal.

  • Any functions accepting callbacks that are not explicitly specified to accept parameters by reference will now warn if a callback with reference parameters is used. Examples include array_filter() and array_reduce(). This was already the case for most, but not all, functions previously.

  • The HTTP stream wrapper as used by functions like file_get_contents() now advertises HTTP/1.1 rather than HTTP/1.0 by default. This does not change the behavior of the client, but may cause servers to respond differently. To retain the old behavior, set the 'protocol_version' stream context option, e.g.

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • Calling crypt() without an explicit salt is no longer supported. If you would like to produce a strong hash with an auto-generated salt, use password_hash() instead.

  • substr(), mb_substr(), iconv_substr() and grapheme_substr() now consistently clamp out-of-bounds offsets to the string boundary. Previously, false was returned instead of the empty string in some cases.

  • On Windows, the program execution functions (proc_open(), exec(), popen() etc.) using the shell, now consistently execute %comspec% /s /c "$commandline", which has the same effect as executing $commandline (without additional quotes).

Sysvsem

  • The auto_release parameter of sem_get() was changed to accept bool values rather than int.

Tidy

  • The use_include_path parameter, which was not used internally, has been removed from tidy_repair_string().

  • tidy::repairString() and tidy::repairFile() became static methods.

Tokenizer

  • T_COMMENT tokens will no longer include a trailing newline. The newline will instead be part of a following T_WHITESPACE token. It should be noted that T_COMMENT is not always followed by whitespace, it may also be followed by T_CLOSE_TAG or end-of-file.

  • Namespaced names are now represented using the T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) and T_NAME_RELATIVE (namespace\Foo\Bar) tokens. T_NS_SEPARATOR is only used for standalone namespace separators, and only syntactially valid in conjunction with group use declarations.

XMLReader

XMLReader::open() and XMLReader::xml() are now static methods. They can still be called as instance methods, but inheriting classes need to declare them as static if they override these methods.

XML-RPC

The XML-RPC extension has been moved to PECL and is no longer part of the PHP distribution.

Zip

ZipArchive::OPSYS_Z_CPM has been removed (this name was a typo). Use ZipArchive::OPSYS_CPM instead.

Zlib

  • gzgetss() has been removed.

  • zlib.output_compression is no longer automatically disabled for Content-Type: image/*.

Windows PHP Test Packs

The test runner has been renamed from run-test.php to run-tests.php, to match its name in php-src.

User Contributed Notes

aphpguy at galaxy dot za dot net 06-Jul-2023 12:33
If you have older projects that break with PHP7 to 8 migration due to the loose comparison issue:

i.e. if ($a == 0) different behaviour between PHP 7 and PHP 8
(for case like $a = "" or $a = "123foo" and other cases listed at top)

replace in old code:

if ($a == 0) { .. }

with

if (cmp_eq($a, $b)) { .. }

Tested with a wide range of scenarios, even against arrays, booleans, file handles, pipe handles, objects, scalars and numbers.

So old code still behave like before.
Then both PHP8.x and older PHP up to ver 7.x will give the exact same boolean true or false output for loose comparisons.

function cmp_eq($a, $b) {
// If both $a and $b are of type strings, compare them as strings
if (is_string($a) && is_string($b)) { return $a == $b; } // may not be === because php says '42' equals '042' true yet '42' === '042' is false.

// If both $a and $b are numeric strings, compare them as numbers
if (is_numeric($a) && is_numeric($b)) { return $a == $b; }

// If $a is an empty string and $b is 0, or vice versa, return true
if (($a === '' && $b === 0) || ($a === 0 && $b === '')) { return true; }

// If $a is a non-numeric string and $b is 0, or vice versa, return true
if ((is_string($a) && ($a !== '') && ($b === 0)) || (($a === 0) && is_string($b) && ($b !== ''))) {
return true;
}
// special case '123abc' == 123 .. php 7 casts 123abc to 123, then 123 == 123 results in true. lets mimic that.
if ((is_string($a) && ($a !== '') && (is_numeric($b)) && ((bool)$b))) {
$number = filter_var($a, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $number == $b;
}
if (is_numeric($a) && ((bool)$a) && is_string($b) && ($b !== '')) {
$number = filter_var($b, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $a == $number;
}

// If $a is a number and $b is a non-numeric string, cast $a to string and compare
if (is_numeric($a) && is_string($b)) { return strval($a) == $b; }

// If $b is a number and $a is a non-numeric string, cast $b to string and compare
if (is_string($a) && is_numeric($b)) { return $a == strval($b); }

// If $a and $b are both non-numeric strings, compare them directly, we should return true if they are the same
return $a == $b;
} // end func cmp_eq

Note: the better way would be to port code to PHP 8, use strict variable typing and rather make use of the === and !== operators.

But in some cases having lots of old code to quickly patch, this might help.
1035041238 at qq dot com 15-Nov-2022 02:41
In PHP 8, an empty string is less than any number, an English letter is always bigger than any number.

More interesting are the punctuation marks and non-word characters, some bigger than numbers, some smaller than numbers

$string = '`~!@#$%^&*()-_=+[]{};:\'"\\|,.<>/?';

$number = 999999999999;

$str_len = strlen($string);

$bigger = $smaller = $equal = [];
for ( $i = 0; $i < $str_len; ++$i ) {
    if ( $string[$i] > $number ) {
        $bigger[] = $string[$i];
    } elseif ( $string[$i] < $number ) {
        $smaller[] = $string[$i];
    } else {
        $equal[] = $string[$i];
    }
}

var_dump( $bigger ); //['`', '~', '@', '^', '_', '=', '[', ']', '{', '}', ';', ':', '\', '|', '<', '>', '?']
var_dump( $smaller); //['!', '#', '$', '%', '&', '*', '(', ')', '-', '+', ''', '"', ',', '.', '/']
var_dump( $equal); //[]
retry, abort, fail 25-Feb-2022 11:57
The change in string to int comparison mentioned above (e.g. '' == 0 now equates to false) has some other nasty consequences:

$a = '';

// php 8

if ( $a < 0 ) echo 'true'; // echos true
if ( $a < -1) echo 'true'; // echos true
if ( $a < -100 ) echo 'true'; // echos true

// php 7

if ( $a < 0 ) echo 'true'; // no output
if ( $a < -1) echo 'true'; // no output
if ( $a < -100 ) echo 'true'; // no output

So in a situation where you may have a web form input and expected an empty value to equate to 0, watch out not only for == 0, != 0, and <= 0 comparisons, but ALL < or <= comparisons to negative integers.


Deprecated Features

PHP Core

  • If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality:

    <?php
    function test($a = [], $b) {} // Before
    function test($a, $b) {} // After
    ?>

    One exception to this rule are parameters of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead:

    <?php
    function test(A $a = null, $b) {} // Still allowed
    function test(?A $a, $b) {} // Recommended
    ?>

  • Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.

Enchant

  • enchant_broker_set_dict_path() and enchant_broker_get_dict_path() are deprecated, because that functionality is neither available in libenchant < 1.5 nor in libenchant-2.

  • enchant_dict_add_to_personal() is deprecated; use enchant_dict_add() instead.

  • enchant_dict_is_in_session() is deprecated; use enchant_dict_is_added() instead.

  • enchant_broker_free() and enchant_broker_free_dict() are deprecated; unset the object instead.

  • The ENCHANT_MYSPELL and ENCHANT_ISPELL constants are deprecated.

LibXML

libxml_disable_entity_loader() has been deprecated. As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default, and this function is no longer needed to protect against XXE attacks, unless the (still vulnerable) LIBXML_NOENT is used. In that case, it is recommended to refactor the code using libxml_set_external_entity_loader() to suppress loading of external entities.

PGSQL / PDO PGSQL

  • The constant PGSQL_LIBPQ_VERSION_STR now has the same value as PGSQL_LIBPQ_VERSION, and thus is deprecated.

  • Function aliases in the pgsql extension have been deprecated. See the following list for which functions should be used instead:

    • pg_errormessage() → pg_last_error()
    • pg_numrows() → pg_num_rows()
    • pg_numfields() → pg_num_fields()
    • pg_cmdtuples() → pg_affected_rows()
    • pg_fieldname() → pg_field_name()
    • pg_fieldsize() → pg_field_size()
    • pg_fieldtype() → pg_field_type()
    • pg_fieldnum() → pg_field_num()
    • pg_result() → pg_fetch_result()
    • pg_fieldprtlen() → pg_field_prtlen()
    • pg_fieldisnull() → pg_field_is_null()
    • pg_freeresult() → pg_free_result()
    • pg_getlastoid() → pg_last_oid()
    • pg_locreate() → pg_lo_create()
    • pg_lounlink() → pg_lo_unlink()
    • pg_loopen() → pg_lo_open()
    • pg_loclose() → pg_lo_close()
    • pg_loread() → pg_lo_read()
    • pg_lowrite() → pg_lo_write()
    • pg_loreadall() → pg_lo_read_all()
    • pg_loimport() → pg_lo_import()
    • pg_loexport() → pg_lo_export()
    • pg_setclientencoding() → pg_set_client_encoding()
    • pg_clientencoding() -> pg_client_encoding()

Standard Library

  • Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.

    <?php
    // Replace
    usort($array, fn($a, $b) => $a > $b);
    // With
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Using an empty file as ZipArchive is deprecated. Libzip 1.6.0 does not accept empty files as valid zip archives any longer. The existing workaround will be removed in the next version.

  • The procedural API of Zip is deprecated. Use ZipArchive instead. Iteration over all entries can be accomplished using ZipArchive::statIndex() and a for loop:

    <?php
    // iterate using the procedural API
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
    echo     zip_entry_name($entry);
    }

    // iterate using the object-oriented API
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
    echo     $entry['name'];
    }
    ?>

Reflection

  • ReflectionFunction::isDisabled() is deprecated, as it is no longer possible to create a ReflectionFunction for a disabled function. This method now always returns false.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), and
ReflectionParameter::isCallable() are deprecated.
ReflectionParameter::getType() and the
ReflectionType APIs should be used instead.

User Contributed Notes

dominique dot vienne at ik dot me 21-Jun-2021 01:23
If you try to get all methods / functions assigning an optional argument before a mandatory one, try this regex (single line)

<?php
function\s+[a-z][a-zA-Z0-9_]*\((?:\$[a-z][a-zA-Z0-9]*\s*,\s*)*
(?:\$[a-z][A-Za-z0-9_]*\s*=[^\$\)]+)+\$[a-z][a-zA-Z0-9_]*\)
?>

for
<?php
public function test($a, $b) {
$a = [];
$b = [$abc => $ss[],
];
}

private function too($c, $a = true, $b) {
}

protected function bar($a = []) {
}

public function foo($a, $b = true) {
}

public function fooBar32($a=true, $b = [], $c) {
}

private function oo_bAr($a = []) {
}
?>
it will match too() and fooBar32()

Have a nice migration! ;)


Other Changes

Changes in SAPI Modules

Apache2Handler

The PHP module has been renamed from php7_module to php_module.

Changed Functions

Reflection

ReflectionClass::getConstants() and ReflectionClass::getReflectionConstants() results can be now filtered via a new parameter filter. Three new constants were added to be used with it:

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Standard

The math functions abs(), ceil(), floor() and round() now properly heed the strict_types directive. Previously, they coerced the first argument even in strict type mode.

Zip

  • The ZipArchive::addGlob() and ZipArchive::addPattern() methods accept more values in the options array argument:

    • flags
    • comp_method
    • comp_flags
    • env_method
    • enc_password

  • ZipArchive::addEmptyDir(), ZipArchive::addFile() and ZipArchive::addFromString() methods have a new flags argument. This allows managing name encoding (ZipArchive::FL_ENC_*) and entry replacement (ZipArchive::FL_OVERWRITE).

  • ZipArchive::extractTo() now restores the file modification time.

Other Changes to Extensions

CURL

  • The CURL extension now requires at least libcurl 7.29.0.

  • The deprecated parameter version of curl_version() has been removed.

Date and Time

DatePeriod now implements IteratorAggregate (instead of Traversable).

DOM

DOMNamedNodeMap and DOMNodeList now implement IteratorAggregate (instead of Traversable).

Intl

IntlBreakIterator and ResourceBundle now implement IteratorAggregate (instead of Traversable).

Enchant

The enchant extension now uses libenchant-2 by default when available. libenchant version 1 is still supported but is deprecated and could be removed in the future.

GD

  • The num_points parameter of imagepolygon(), imageopenpolygon() and imagefilledpolygon() is now optional, i.e. these functions may be called with either 3 or 4 arguments. If the argument is omitted, it is calculated as count($points)/2.

  • The function imagegetinterpolation() to get the current interpolation method has been added.

JSON

The JSON extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

MBString

The Unicode data tables have been updated to version 13.0.0.

PDO

PDOStatement now implements IteratorAggregate (instead of Traversable).

LibXML

The minimum required libxml version is now 2.9.0. This means that external entity loading is now guaranteed to be disabled by default, and no extra steps need to be taken to protect against XXE attacks.

MySQLi / PDO MySQL

  • When mysqlnd is not used (which is the default and recommended option), the minimum supported libmysqlclient version is now 5.5.

  • mysqli_result now implements IteratorAggregate (instead of Traversable).

PGSQL / PDO PGSQL

The PGSQL and PDO PGSQL extensions now require at least libpq 9.1.

Readline

Calling readline_completion_function() before the interactive prompt starts (e.g. in auto_prepend_file) will now override the default interactive prompt completion function. Previously, readline_completion_function() only worked when called after starting the interactive prompt.

SimpleXML

SimpleXMLElement now implements RecursiveIterator and absorbed the functionality of SimpleXMLIterator. SimpleXMLIterator is an empty extension of SimpleXMLElement.

Changes to INI File Handling

  • com.dotnet_version is a new INI directive to choose the version of the .NET framework to use for dotnet objects.

  • zend.exception_string_param_max_len is a new INI directive to set the maximum string length in an argument of a stringified stack strace.

EBCDIC

EBCDIC targets are no longer supported, though it's unlikely that they were still working in the first place.

Performance

  • A Just-In-Time (JIT) compiler has been added to the opcache extension.

  • array_slice() on an array without gaps will no longer scan the whole array to find the start offset. This may significantly reduce the runtime of the function with large offsets and small lengths.

  • strtolower() now uses a SIMD implementation when using the "C" LC_CTYPE locale (which is the default).

User Contributed Notes

barry dot nelson at amobiledevice dot com 16-Jan-2023 12:18
If loading the PHP8 apache module on SuSe Linux, the configuration scripts incorrectly try to load it with automatically generated load statement of:
LoadModule php8_module                     /usr/lib64/apache2/mod_php8.so
This does not work, the patch below fixes the conf file generator...

--- /usr/share/apache2/get_module_list    2023-01-14 22:41:49.586825349 -0500
+++ /usr/share/apache2/get_module_list    2023-01-14 22:42:02.171600410 -0500
@@ -91,4 +91,8 @@
     esac

+    if [ "$module_id" = "php8_module" ]; then
+        module_id="php_module"
+    fi
+
     if [[ -f $module_path ]]; then
         printf "LoadModule %-30s %s\n" $module_id $module_path >&3


Migrating from PHP 7.3.x to PHP 7.4.x

Table of Contents

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Removed Extensions
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x, 7.1.x, 7.2.x and 7.3.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Typed properties

Class properties now support type declarations.

<?php
class User {
public int $id;
public string $name;
}
?>
The above example will enforce that $user->id can only be assigned int values and $user->name can only be assigned string values.

Arrow functions

Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Limited return type covariance and argument type contravariance

The following code will now work:

<?php
class A {}
class B extends A {}

class Producer {
public function method(): A {}
}
class ChildProducer extends Producer {
public function method(): B {}
}
?>
Full variance support is only available if autoloading is used. Inside a single file only non-cyclic type references are possible, because all classes need to be available before they are referenced.

Null coalescing assignment operator

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
?>

Unpacking inside arrays

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Numeric literal separator

Numeric literals can contain underscores between digits.

<?php
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
?>

Weak references

Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.

Allow exceptions from __toString()

Throwing exceptions from __toString() is now permitted. Previously this resulted in a fatal error. Existing recoverable fatal errors in string conversions have been converted to Error exceptions.

CURL

CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.

Filter

The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

FFI

FFI is a new extension, which provides a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

GD

Added the IMG_FILTER_SCATTER image filter to apply a scatter filter to images.

Hash

Added crc32c hash using Castagnoli's polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

Multibyte String

Added the mb_str_split() function, which provides the same functionality as str_split(), but operating on code points rather than bytes.

OPcache

Support for preloading code has been added.

Regular Expressions (Perl-Compatible)

The preg_replace_callback() and preg_replace_callback_array() functions now accept an additional flags argument, with support for the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the format of the matches array passed to the callback function.

PDO

The username and password can now be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this was only supported by the pgsql driver. If a username/password is specified both in the constructor and the DSN, the constructor takes precedence.

It is now possible to escape question marks in SQL queries to avoid them being interpreted as parameter placeholders. Writing ?? allows sending a single question mark to the database and e.g. use the PostgreSQL JSON key exists (?) operator.

PDO_OCI

PDOStatement::getColumnMeta() is now available.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows checking whether the statement is read-only, i.e. if it doesn't modify the database.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the use of SQLite3 extended result codes in PDO::errorInfo() and PDOStatement::errorInfo().

SQLite3

Added SQLite3::lastExtendedErrorCode() to fetch the last extended result code.

Added SQLite3::enableExtendedResultCodes($enable = true), which will make SQLite3::lastErrorCode() return extended result codes.

Standard

strip_tags() with array of tag names

strip_tags() now also accepts an array of allowed tags: instead of strip_tags($str, '<a><p>') you can now write strip_tags($str, ['a', 'p']).

Custom object serialization

A new mechanism for custom object serialization has been added, which uses two new magic methods: __serialize and __unserialize.

<?php
// Returns array containing all the necessary state of the object.
public function __serialize(): array;

// Restores the object state from the given data array.
public function __unserialize(array $data): void;
?>
The new serialization mechanism supersedes the Serializable interface, which will be deprecated in the future.

Array merge functions without arguments

array_merge() and array_merge_recursive() may now be called without any arguments, in which case they will return an empty array. This is useful in conjunction with the spread operator, e.g. array_merge(...$arrays).

proc_open() function

proc_open() now accepts an array instead of a string for the command. In this case the process will be opened directly (without going through a shell) and PHP will take care of any necessary argument escaping.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() now supports redirect and null descriptors.

<?php
// Like 2>&1 on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) without libargon

password_hash() now has the argon2i and argon2id implementations from the sodium extension when PHP is built without libargon.

User Contributed Notes

wow-apps.pro 26-Feb-2020 08:42
<?php

// How to get property type? For example for testing:

class Foo
{
    private int $num;
    private bool $isPositive;
    private $notes;
}

$reflection = new \ReflectionClass(Foo::class);
$classProperties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
foreach ($classProperties as $classProperty) {
    var_dump((string) $classProperty->getType());
}

/**
 * Result:
 * "int"
 * "bool"
 * ""
 */
Rain 27-Jan-2020 08:44
It should be noted that typed properties internally are never initialized to a default null. Unless of course you initialize them to null yourself. That's why you will always going to encounter this error if you try to access them before initialization.

**Typed property foo::$bar must not be accessed before initialization**

<?php
class User
{
    public $id;
    public string $name; // Typed property (Uninitialized)
    public ?string $age = null; //  Typed property (Initialized)
}

$user = new User;
var_dump(is_null($user->id)); // bool(true)
var_dump(is_null($user->name)); // PHP Fatal error: Typed property User::$name must not be accessed before initialization
var_dump(is_null($user->age));// bool(true)
?>

Another thing worth noting is that it's not possible to initialize a property of type object to anything other than null.  Since the evaluation of properties happens at compile-time and object instantiation happens at runtime. One last thing, callable type is not supported due to its context-dependent behavior.


New Classes and Interfaces

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


New Functions

PHP Core

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

Multibyte String

  • mb_str_split()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

PHP Core

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

Added the following FreeBSD-specific socket options:

  • SO_LABEL
  • SO_PEERLABEL
  • SO_LISTENQLIMIT
  • SO_LISTENQLEN
  • SO_USER_COOKIE

Tidy

  • TIDY_TAG_ARTICLE
  • TIDY_TAG_ASIDE
  • TIDY_TAG_AUDIO
  • TIDY_TAG_BDI
  • TIDY_TAG_CANVAS
  • TIDY_TAG_COMMAND
  • TIDY_TAG_DATALIST
  • TIDY_TAG_DETAILS
  • TIDY_TAG_DIALOG
  • TIDY_TAG_FIGCAPTION
  • TIDY_TAG_FIGURE
  • TIDY_TAG_FOOTER
  • TIDY_TAG_HEADER
  • TIDY_TAG_HGROUP
  • TIDY_TAG_MAIN
  • TIDY_TAG_MARK
  • TIDY_TAG_MENUITEM
  • TIDY_TAG_METER
  • TIDY_TAG_NAV
  • TIDY_TAG_OUTPUT
  • TIDY_TAG_PROGRESS
  • TIDY_TAG_SECTION
  • TIDY_TAG_SOURCE
  • TIDY_TAG_SUMMARY
  • TIDY_TAG_TEMPLATE
  • TIDY_TAG_TIME
  • TIDY_TAG_TRACK
  • TIDY_TAG_VIDEO

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Array-style access of non-arrays

Trying to use values of type null, bool, int, float or resource as an array (such as $null["key"]) will now generate a notice.

get_declared_classes() function

The get_declared_classes() function no longer returns anonymous classes that have not been instantiated yet.

fn keyword

fn is now a reserved keyword. In particular, it can no longer be used as a function or class name. It can still be used as a method or class constant name.

<?php tag at end of file

<?php at the end of the file (without trailing newline) will now be interpreted as an opening PHP tag. Previously it was interpreted either as a short opening tag followed by literal php and resulted in a syntax error (with short_open_tag=1) or was interpreted as a literal <?php string (with short_open_tag=0).

Stream wrappers

When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper implementations may need to implement the streamWrapper::stream_set_option() method to avoid a warning (always returning false is a sufficient implementation).

Serialization

The o serialization format has been removed. As it is never produced by PHP, this may only break unserialization of manually crafted strings.

Password algorithm constants

Password hashing algorithm identifiers are now nullable strings rather than integers.

  • PASSWORD_DEFAULT was int 1; now is string '2y' (in PHP 7.4.0, 7.4.1, and 7.4.2 it was null)
  • PASSWORD_BCRYPT was int 1; now is string '2y'
  • PASSWORD_ARGON2I was int 2; now is string 'argon2i'
  • PASSWORD_ARGON2ID was int 3; now is string 'argon2id'

Applications correctly using the constants PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, and PASSWORD_ARGON2ID will continue to function correctly.

htmlentities() function

htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

fread() and fwrite() function

fread() and fwrite() will now return false if the operation failed. Previously an empty string or 0 was returned. EAGAIN/EWOULDBLOCK are not considered failures.

These functions now also raise a notice on failure, such as when trying to write to a read-only file resource.

BCMath Arbitrary Precision Mathematics

BCMath functions will now warn if a non well-formed number is passed, such as "32foo". The argument will be interpreted as zero, as before.

CURL

Attempting to serialize a CURLFile class will now generate an exception. Previously the exception was only thrown on unserialization.

Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL 7.62.0.

The $version parameter of curl_version() is deprecated. If any value not equal to the default CURLVERSION_NOW is passed, a warning is raised and the parameter is ignored.

Date and Time

Calling var_dump() or similar on a DateTime or DateTimeImmutable instance will no longer leave behind accessible properties on the object.

Comparison of DateInterval objects (using ==, <, and so on) will now generate a warning and always return false. Previously all DateInterval objects were considered equal, unless they had properties.

Intl

The default parameter value of idn_to_ascii() and idn_to_utf8() is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

MySQLi

The embedded server functionality has been removed. It was broken since at least PHP 7.0.

The undocumented mysqli::$stat property has been removed in favor of mysqli::stat().

OpenSSL

The openssl_random_pseudo_bytes() function will now throw an exception in error situations, similar to random_bytes(). In particular, an Error is thrown if the number of requested bytes is less than or equal to zero, and an Exception is thrown if sufficient randomness cannot be gathered. The $crypto_strong output argument is guaranteed to always be true if the function does not throw, so explicitly checking it is not necessary.

Regular Expressions (Perl-Compatible)

When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing groups will now also be set to null (or [null, -1] if offset capture is enabled). This means that the size of the $matches will always be the same.

PHP Data Objects

Attempting to serialize a PDO or PDOStatement instance will now generate an Exception rather than a PDOException, consistent with other internal classes which do not support serialization.

Reflection

Reflection objects will now generate an exception if an attempt is made to serialize them. Serialization for reflection objects was never supported and resulted in corrupted reflection objects. It has been explicitly prohibited now.

The values of the class constant of ReflectionClassConstant, ReflectionMethod and ReflectionProperty have changed.

Standard PHP Library (SPL)

Calling get_object_vars() on an ArrayObject instance will now always return the properties of the ArrayObject itself (or a subclass). Previously it returned the values of the wrapped array/object unless the ArrayObject::STD_PROP_LIST flag was specified.

Other affected operations are:

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Use Iterator methods instead.
  • Potentially others working on object properties as a list, e.g. array_walk().

(array) casts are not affected. They will continue to return either the wrapped array, or the ArrayObject properties, depending on whether the ArrayObject::STD_PROP_LIST flag is used.

SplPriorityQueue::setExtractFlags() will throw an exception if zero is passed. Previously this would generate a recoverable fatal error on the next extraction operation.

ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now support the __serialize() and __unserialize() mechanism in addition to the Serializable interface. This means that serialization payloads created on older PHP versions can still be unserialized, but new payloads created by PHP 7.4 will not be understood by older versions.

Tokenizer

token_get_all() will now emit a T_BAD_CHARACTER token for unexpected characters instead of leaving behind holes in the token stream.

Incoming Cookies

As of PHP 7.4.11, the names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

happydog at kennel17 24-Jan-2021 11:23
Re: "The o serialization format has been removed. As it is never produced by PHP, this may only break unserialization of manually crafted strings."

This little-o serialisation format was used by PHP3 but was never generated by PH PHP4 or above.  The deserialization code still recognised it, though, for reasons of backwards-compatibility with PHP3.

However, based on a bit of investigation, it looks like this code has been broken for about 15 years, so although this is listed as a deprecation, in practice it wasn't.

See this Stack Overflow question for a really great answer, with a lot more detail about this: https://stackoverflow.com/questions/65289729/what-was-phps-o-serialization-format-for


Deprecated Features

PHP Core

Nested ternary operators without explicit parentheses

Nested ternary operations must explicitly use parentheses to dictate the order of the operations. Previously, when used without parentheses, the left-associativity would not result in the expected behaviour in most cases.

<?php
1 ? 2 : 3 ? 4 : 5; // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Parentheses are not required when nesting into the middle operand, as this is always unambiguous and not affected by associativity:

1 ? 2 ? 3 : 4 : 5 // ok

Array and string offset access using curly braces

The array and string offset access syntax using curly braces is deprecated. Use $var[$idx] instead of $var{$idx}.

(real) cast and is_real() function

The (real) cast is deprecated, use (float) instead.

The is_real() function is also deprecated, use is_float() instead.

Unbinding $this when $this is used

Unbinding $this of a non-static closure that uses $this is deprecated.

parent keyword without parent class

Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.

allow_url_include INI option

The allow_url_include ini directive is deprecated. Enabling it will generate a deprecation notice at startup.

Invalid characters in base conversion functions

Passing invalid characters to base_convert(), bindec(), octdec() and hexdec() will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist. Leading and trailing whitespace, as well as prefixes of type 0x (depending on base) continue to be allowed.

Using array_key_exists() on objects

Using array_key_exists() on objects is deprecated. Instead either isset() or property_exists() should be used.

Magic quotes functions

The get_magic_quotes_gpc() and get_magic_quotes_runtime() functions are deprecated. They always return false.

hebrevc() function

The hebrevc() function is deprecated. It can be replaced with nl2br(hebrev($str)) or, preferably, the use of Unicode RTL support.

convert_cyr_string() function

The convert_cyr_string() function is deprecated. It can be replaced by one of mb_convert_string(), iconv() or UConverter.

money_format() function

The money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality.

ezmlm_hash() function

The ezmlm_hash() function is deprecated.

restore_include_path() function

The restore_include_path() function is deprecated. It can be replaced by ini_restore('include_path').

Implode with historical parameter order

Passing parameters to implode() in reverse order is deprecated, use implode($glue, $parts) instead of implode($parts, $glue).

COM

Importing type libraries with case-insensitive constant registering has been deprecated.

Filter

FILTER_SANITIZE_MAGIC_QUOTES is deprecated, use FILTER_SANITIZE_ADD_SLASHES instead.

Multibyte String

Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently, non-string patterns are interpreted as ASCII codepoints. In PHP 8, the pattern will be interpreted as a string instead.

Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead pass a 0 offset, and encoding as 4th parameter.

Lightweight Directory Access Protocol

ldap_control_paged_result_response() and ldap_control_paged_result() are deprecated. Pagination controls can be sent along with ldap_search() instead.

Reflection

Calls to ReflectionType::__toString() now generate a deprecation notice. This method has been deprecated in favor of ReflectionNamedType::getName() in the documentation since PHP 7.1, but did not throw a deprecation notice for technical reasons.

The export() methods on all Reflection classes are deprecated. Construct a Reflection object and convert it to string instead:

<?php
// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

The AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() are deprecated, due to an upstream deprecation in 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


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

  • Firebird/Interbase - access to an InterBase and/or Firebird based database is still available with the PDO Firebird driver.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Performance Improvements

PHP Core

A specialized VM opcode for the array_key_exists() function has been added, which improves performance of this function if it can be statically resolved. In namespaced code, this may require writing \array_key_exists() or explicitly importing the function.

Regular Expressions (Perl-Compatible)

When preg_match() in UTF-8 mode ("u" modifier) is repeatedly called on the same string (but possibly different offsets), it will only be checked for UTF-8 validity once.

Changes to INI File Handling

zend.exception_ignore_args is a new INI directive for including or excluding arguments from stack traces generated from exceptions.

opcache.preload_user is a new INI directive for specifying the user account under which preloading code is execute if it would otherwise be run as root (which is not allowed for security reasons).

Migration to pkg-config

A number of extensions have been migrated to exclusively use pkg-config for the detection of library dependencies. Generally, this means that instead of using --with-foo-dir=DIR or similar only --with-foo is used. Custom library paths can be specified either by adding additional directories to PKG_CONFIG_PATH or by explicitly specifying compilation options through FOO_CFLAGS and FOO_LIBS.

The following extensions and SAPIs are affected:

  • CURL:
    • --with-curl no longer accepts a directory.
  • Enchant:
    • --with-enchant no longer accepts a directory.
  • FPM:
    • --with-fpm-systemd now uses only pkg-config for libsystem checks. The libsystemd minimum required version is 209.
  • GD:
    • --with-gd becomes --enable-gd (whether to enable the extension at all) and --with-external-gd (to opt into using an external libgd, rather than the bundled one).
    • --with-png-dir has been removed. libpng is required.
    • --with-zlib-dir has been removed. zlib is required.
    • --with-freetype-dir becomes --with-freetype
    • --with-jpeg-dir becomes --with-jpeg
    • --with-webp-dir becomes --with-webp
    • --with-xpm-dir becomes --with-xpm
  • IMAP:
    • --with-kerberos-systemd no longer accepts a directory.
  • Intl:
    • --with-icu-dir has been removed. If --enable-intl is passed, then libicu is always required.
  • LDAP:
    • --with-ldap-sasl no longer accepts a directory.
  • Libxml:
    • --with-libxml-dir has been removed.
    • --enable-libxml becomes --with-libxml.
    • --with-libexpat-dir has been renamed to --with-expat and no longer accepts a directory.
  • Litespeed:
    • --with-litespeed becomes --enable-litespeed.
  • Mbstring:
    • --with-onig has been removed. Unless --disable-mbregex has been passed, libonig is required.
  • ODBC:
    • --with-iodbc no longer accepts a directory.
    • --with-unixODBC without a directory now uses pkg-config (preferred). Directory is still accepted for old versions without libodbc.pc.
  • OpenSSL:
    • --with-openssl no longer accepts a directory.
  • PCRE:
    • --with-pcre-regex has been removed. Instead --with-external-pcre is provided to opt into using an external PCRE library, rather than the bundled one.
  • PDO_SQLite:
    • --with-pdo-sqlite no longer accepts a directory.
  • Readline:
    • --with-libedit no longer accepts a directory.
  • Sodium:
    • --with-sodium no longer accepts a directory.
  • SQLite3:
    • --with-sqlite3 no longer accepts a directory.
  • XSL:
    • --with-xsl no longer accepts a directory.
  • Zip:
    • --with-libzip has been removed.
    • --enable-zip becomes --with-zip.

CSV escaping

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), and
SplFileObject::setCsvControl()
now accept an empty string as $escape argument,
which disables the proprietary PHP escaping mechanism.

The behavior of str_getcsv() has been adjusted accordingly (formerly, an empty string was identical to using the default).

SplFileObject::getCsvControl() now may also return an empty string for the third array element, accordingly.

Data Filtering

The filter extension no longer exposes --with-pcre-dir for Unix builds and can now reliably be built as shared when using ./configure

GD

The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd:

  • IMG_CROP_DEFAULT is no longer falling back to IMG_CROP_SIDES
  • Threshold-cropping now uses the algorithm of system libgd

The default $mode parameter of imagecropauto() has been changed to IMG_CROP_DEFAULT; passing -1 is now deprecated.

imagescale() now supports aspect ratio preserving scaling to a fixed height by passing -1 as $new_width.

HASH Message Digest Framework

The hash extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

Intl

The intl extension now requires at least ICU 50.1.

ResourceBundle now implements Countable.

Lightweight Directory Access Protocol

Support for nsldap and umich_ldap has been removed.

Libxml

All libxml-based extensions now require libxml 2.7.6 or newer.

Multibyte String

The oniguruma library is no longer bundled with PHP, instead libonig needs to be available on the system. Alternatively --disable-mbregex can be used to disable the mbregex component.

OPcache

The --disable-opcache-file and --enable-opcache-file configure options have been removed in favor of the opcache.file_cache INI directive.

Password Hashing

The password_hash() and password_needs_rehash() functions now accept nullable string and int for $algo argument.

PEAR

Installation of PEAR (including PECL) is no longer enabled by default. It can be explicitly enabled using --with-pear. This option is deprecated and may be removed in the future.

Reflection

The numeric values of the modifier constants (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, and IS_STATIC) on the ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, and ReflectionProperty classes have changed.

SimpleXML

SimpleXMLElement now implements Countable.

SQLite3

The bundled libsqlite has been removed. To build the SQLite3 extension a system libsqlite3 ≥ 3.7.4 is now required. To build the PDO_SQLite extension a system libsqlite3 ≥ 3.5.0 is now required.

Serialization and unserialization of SQLite3, SQLite3Stmt and SQLite3Result is now explicitly forbidden. Formerly, serialization of instances of these classes was possible, but unserialization yielded unusable objects.

The @param notation can now also be used to denote SQL query parameters.

Zip

The bundled libzip library has been removed. A system libzip >= 0.11 is now necessary to build the zip extension.

User Contributed Notes

santi at mola dot io 31-Jul-2020 07:54
Note for internals/extensions:

Many opcode values changed between PHP 7.3 and 7.4, so most documentation resources are outdated in that regard. You can look the definitions at Zend/zend_vm_opcodes.h in php-src. For example, ZEND_ECHO changes from 40 to 136.

While opcode changes happen in a lot of PHP versions, the change in 7.4 is quite significant.
ohcc at 163 dot com 09-Jun-2020 04:56
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
Florent H (Sowapps) 16-Feb-2020 07:37
This version brings an important changes with the directive zend.exception_ignore_args set to On by default.
In all stack traces, the args key is now missing.
All php frameworks have to handle this to report errors & exceptions.


Windows Support

configure flags

configure now regards additional CFLAGS and LDFLAGS set as environment variables.

CTRL handling

CTRL+C and CTRL+BREAK on console can be caught by setting a handler function with sapi_windows_set_ctrl_handler().

proc_open() on Windows can be passed a "create_process_group" option. It is required if the child process is supposed to handle CTRL events.

OPcache

OPcache now supports an arbitrary number of separate caches per user via the INI directive opcache.cache_id. All processes with the same cache ID and user share an OPcache instance.

stat

The stat implementation has been refactored.

  • An inode number is delivered and is based on the NTFS file index.
  • The device number is now based on the volume serial number.

Note that both values are derived from the system and provided as-is on 64-bit systems. On 32-bit systems, these values might overflow the 32-bit integer in PHP, so they're fake.

libsqlite3

libsqlite3 is no longer compiled statically into php_sqlite3.dll and php_pdo_sqlite.dll, but rather available as libsqlite3.dll. Refer to the installation instructions for SQLite3 and PDO_SQLITE, respectively.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 7.2.x to PHP 7.3.x

Table of Contents

  • New Features
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x, 7.1.x and 7.2.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

More Flexible Heredoc and Nowdoc Syntax

The closing marker for doc strings is no longer required to be followed by a semicolon or newline. Additionally the closing marker may be indented, in which case the indentation will be stripped from all lines in the doc string.

Array Destructuring supports Reference Assignments

Array destructuring now supports reference assignments using the syntax [&$a, [$b, &$c]] = $d. The same is also supported for list().

Instanceof Operator accepts Literals

instanceof now allows literals as the first operand, in which case the result is always false.

CompileError Exception instead of some Compilation Errors

A new CompileError exception has been added, from which ParseError inherits. A small number of compilation errors will now throw a CompileError instead of generating a fatal error. Currently this only affects compilation errors that may be thrown by token_get_all() in TOKEN_PARSE mode, but more errors may be converted in the future.

Trailing Commas are allowed in Calls

Trailing commas in function and method calls are now allowed.

Argon2id Support

The --with-password-argon2[=dir] configure argument now provides support for both Argon2i and Argon2id hashes in the password_hash(), password_verify(), password_get_info(), and password_needs_rehash() functions. Passwords may be hashed and verified using the PASSWORD_ARGON2ID constant. Support for both Argon2i and Argon2id in the password_*() functions now requires PHP be linked against libargon2 reference library ≥ 20161029.

FastCGI Process Manager

New options have been added to customize the FPM logging:

log_limit
This global option can be used for setting the log limit for the logged line which allows to log messages longer than 1024 characters without wrapping. It also fixes various wrapping issues.
log_buffering
This global option allows an experimental logging without extra buffering.
decorate_workers_output
This pool option allows to disable the output decoration for workers output when catch_workers_output is enabled.

BC Math Functions

bcscale() can now also be used as getter to retrieve the current scale in use.

Lightweight Directory Access Protocol

Full support for LDAP Controls has been added to the LDAP querying functions and ldap_parse_result():

  • A $serverctrls parameter to send controls to the
server in ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() and
ldap_read() has been added.
  • The out parameter $serverctrls to get controls from the server in ldap_parse_result() has been added.
  • Support for LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS in ldap_get_option() and ldap_set_option() has been fixed.

Multibyte String Functions

Full Case-Mapping and Case-Folding Support

Support for full case-mapping and case-folding has been added. Unlike simple case-mapping, full case-mapping may change the length of the string. For example:

<?php
mb_strtoupper("Straße");
// Produces STRAßE on PHP 7.2
// Produces STRASSE on PHP 7.3
?>
The different casing mapping and folding modes are available through mb_convert_case():
  • MB_CASE_LOWER (used by mb_strtolower())
  • MB_CASE_UPPER (used by mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (used by case-insensitive operations)
Only unconditional, language agnostic full case-mapping is performed.

Case-Insensitive String Operations use Case-Folding

Case-insensitive string operations now use case-folding instead of case- mapping during comparisons. This means that more characters will be considered (case insensitively) equal now.

MB_CASE_TITLE performs Title-Case Conversion

mb_convert_case() with MB_CASE_TITLE now performs title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this also improves handling of quotes and apostrophes.

Unicode 11 Support

The Multibyte String data tables have been updated for Unicode 11.

Long String Support

The Multibyte String Functions now correctly support strings larger than 2GB.

Performance Improvements

Performance of the Multibyte String extension has been significantly improved across the board. The largest improvements are in case conversion functions.

Named Captures Support

The mb_ereg_* functions now support named captures. Matching functions like mb_ereg() will now return named captures both using their group number and their name, similar to PCRE:

<?php
mb_ereg('(?<word>\w+)', '国', $matches);
// => [0 => "国", 1 => "国", "word" => "国"];
?>
Additionally, mb_ereg_replace() now supports the \k<> and \k'' notations to reference named captures in the replacement string:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> and \k'' can also be used for numbered references, which also works with group numbers greater than 9.

Readline

Support for the completion_append_character and completion_suppress_append options has been added to readline_info(). These options are only available if PHP is linked against libreadline (rather than libedit).

User Contributed Notes

yoander dot valdes at yahoo dot com 31-May-2019 11:34
"Trailing commas in function and method calls are now allowed" means function parameters, example:

<?php

function my1() {
        echo "xxxxxx\n";
}

function my2() {
        echo "yyyyyy\n";
}

my1(),my2(); // PHP Parse error:  syntax error

my1(,); // PHP Parse error:  syntax error

my1(1,); my2(2,); // OK

?>


New Functions

PHP Core

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI Process Manager

  • fpm_get_status()

Date and Time

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


New Global Constants

PHP Core

  • PASSWORD_ARGON2ID

Client URL Library

  • CURLAUTH_BEARER
  • CURLAUTH_GSSAPI
  • CURLE_WEIRD_SERVER_REPLY
  • CURLINFO_APPCONNECT_TIME_T
  • CURLINFO_CONNECT_TIME_T
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T
  • CURLINFO_FILETIME_T
  • CURLINFO_HTTP_VERSION
  • CURLINFO_NAMELOOKUP_TIME_T
  • CURLINFO_PRETRANSFER_TIME_T
  • CURLINFO_PROTOCOL
  • CURLINFO_PROXY_SSL_VERIFYRESULT
  • CURLINFO_REDIRECT_TIME_T
  • CURLINFO_SCHEME
  • CURLINFO_SIZE_DOWNLOAD_T
  • CURLINFO_SIZE_UPLOAD_T
  • CURLINFO_SPEED_DOWNLOAD_T
  • CURLINFO_SPEED_UPLOAD_T
  • CURLINFO_STARTTRANSFER_TIME_T
  • CURLINFO_TOTAL_TIME_T
  • CURL_LOCK_DATA_CONNECT
  • CURL_LOCK_DATA_PSL
  • CURL_MAX_READ_SIZE
  • CURLOPT_ABSTRACT_UNIX_SOCKET
  • CURLOPT_DISALLOW_USERNAME_IN_URL
  • CURLOPT_DNS_SHUFFLE_ADDRESSES
  • CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
  • CURLOPT_HAPROXYPROTOCOL
  • CURLOPT_KEEP_SENDING_ON_ERROR
  • CURLOPT_PRE_PROXY
  • CURLOPT_PROXY_CAINFO
  • CURLOPT_PROXY_CAPATH
  • CURLOPT_PROXY_CRLFILE
  • CURLOPT_PROXY_KEYPASSWD
  • CURLOPT_PROXY_PINNEDPUBLICKEY
  • CURLOPT_PROXY_SSLCERT
  • CURLOPT_PROXY_SSLCERTTYPE
  • CURLOPT_PROXY_SSL_CIPHER_LIST
  • CURLOPT_PROXY_SSLKEY
  • CURLOPT_PROXY_SSLKEYTYPE
  • CURLOPT_PROXY_SSL_OPTIONS
  • CURLOPT_PROXY_SSL_VERIFYHOST
  • CURLOPT_PROXY_SSL_VERIFYPEER
  • CURLOPT_PROXY_SSLVERSION
  • CURLOPT_PROXY_TLS13_CIPHERS
  • CURLOPT_PROXY_TLSAUTH_PASSWORD
  • CURLOPT_PROXY_TLSAUTH_TYPE
  • CURLOPT_PROXY_TLSAUTH_USERNAME
  • CURLOPT_REQUEST_TARGET
  • CURLOPT_SOCKS5_AUTH
  • CURLOPT_SSH_COMPRESSION
  • CURLOPT_SUPPRESS_CONNECT_HEADERS
  • CURLOPT_TIMEVALUE_LARGE
  • CURLOPT_TLS13_CIPHERS
  • CURLPROXY_HTTPS
  • CURLSSH_AUTH_GSSAPI
  • CURL_SSLVERSION_MAX_DEFAULT
  • CURL_SSLVERSION_MAX_NONE
  • CURL_SSLVERSION_MAX_TLSv1_0
  • CURL_SSLVERSION_MAX_TLSv1_1
  • CURL_SSLVERSION_MAX_TLSv1_2
  • CURL_SSLVERSION_MAX_TLSv1_3
  • CURL_SSLVERSION_TLSv1_3
  • CURL_VERSION_ALTSVC (as of PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (as of PHP 7.3.6)
  • CURL_VERSION_DEBUG
  • CURL_VERSION_GSSAPI
  • CURL_VERSION_GSSNEGOTIATE
  • CURL_VERSION_HTTPS_PROXY
  • CURL_VERSION_IDN
  • CURL_VERSION_LARGEFILE
  • CURL_VERSION_MULTI_SSL
  • CURL_VERSION_NTLM
  • CURL_VERSION_NTLM_WB
  • CURL_VERSION_PSL (as of PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Data Filtering

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

  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE

OpenSSL

  • STREAM_CRYPTO_PROTO_SSLv3
  • STREAM_CRYPTO_PROTO_TLSv1_0
  • STREAM_CRYPTO_PROTO_TLSv1_1
  • STREAM_CRYPTO_PROTO_TLSv1_2

PostgreSQL

  • PGSQL_DIAG_SCHEMA_NAME
  • PGSQL_DIAG_TABLE_NAME
  • PGSQL_DIAG_COLUMN_NAME
  • PGSQL_DIAG_DATATYPE_NAME
  • PGSQL_DIAG_CONSTRAINT_NAME
  • PGSQL_DIAG_SEVERITY_NONLOCALIZED

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Heredoc/Nowdoc Ending Label Interpretation

Due to the introduction of flexible heredoc/nowdoc syntax, doc strings that contain the ending label inside their body may cause syntax errors or change in interpretation. For example in:

<?php
$str = <<<FOO
abcdefg
 FOO
FOO;
?>
the indented occurrence of FOO did not previously have any special meaning. Now it will be interpreted as the end of the heredoc string and the following FOO; will cause a syntax error. This issue can always be resolved by choosing an ending label that does not occur within the contents of the string.

Continue Targeting Switch issues Warning

continue statements targeting switch control flow structures will now generate a warning. In PHP such continue statements are equivalent to break, while they behave as continue 2 in other languages.

<?php
while ($foo) {
switch ($bar) {
case "baz":
continue;
// Warning: "continue" targeting switch is equivalent to
// "break". Did you mean to use "continue 2"?
}
}
?>

Strict Interpretation of Integer String Keys on ArrayAccess

Array accesses of type $obj["123"], where $obj implements ArrayAccess and "123" is an integer string literal will no longer result in an implicit conversion to integer, i.e., $obj->offsetGet("123") will be called instead of $obj->offsetGet(123). This matches existing behavior for non-literals. The behavior of arrays is not affected in any way, they continue to implicitly convert integral string keys to integers.

Static Properties no longer separated by Reference Assignment

In PHP, static properties are shared between inheriting classes, unless the static property is explicitly overridden in a child class. However, due to an implementation artifact it was possible to separate the static properties by assigning a reference. This loophole has been fixed.

<?php
class Test {
public static $x = 0;
}
class Test2 extends Test { }

Test2::$x = &$x;
$x = 1;

var_dump(Test::$x, Test2::$x);
// Previously: int(0), int(1)
// Now: int(1), int(1)
?>

References returned by Array and Property Accesses are immediately unwrapped

References returned by array and property accesses are now unwrapped as part of the access. This means that it is no longer possible to modify the reference between the access and the use of the accessed value:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
This makes the behavior of references and non-references consistent. Please note that reading and writing a value inside a single expression remains undefined behavior and may change again in the future.

Argument Unpacking of Traversables with non-Integer Keys no longer supported

Argument unpacking stopped working with Traversables with non-integer keys. The following code worked in PHP 5.6-7.2 by accident.

<?php
function foo(...$args) {
var_dump($args);
}
function gen() {
yield 1.23 => 123;
}
foo(...gen());
?>

Miscellaneous

The ext_skel utility has been completely redesigned with new options and some old options removed. This is now written in PHP and has no external dependencies.

Support for BeOS has been dropped.

Exceptions thrown due to automatic conversion of warnings into exceptions in EH_THROW mode (e.g. some DateTime exceptions) no longer populate error_get_last() state. As such, they now work the same way as manually thrown exceptions.

TypeError now reports wrong types as int and bool instead of integer and boolean, respectively.

Undefined variables passed to compact() will now be reported as a notice.

getimagesize() and related functions now report the mime type of BMP images as image/bmp instead of image/x-ms-bmp, since the former has been registered with the IANA (see » RFC 7903).

stream_socket_get_name() will now return IPv6 addresses wrapped in brackets. For example "[::1]:1337" will be returned instead of "::1:1337".

BCMath Arbitrary Precision Mathematics

All warnings thrown by BCMath functions are now using PHP's error handling. Formerly some warnings have directly been written to stderr.

bcmul() and bcpow() now return numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

IMAP, POP3 and NNTP

rsh/ssh logins are disabled by default. Use imap.enable_insecure_rsh if you want to enable them. Note that the IMAP library does not filter mailbox names before passing them to the rsh/ssh command, thus passing untrusted data to this function with rsh/ssh enabled is insecure.

Multibyte String

Due to added support for named captures, mb_ereg_*() patterns using named captures will behave differently. In particular named captures will be part of matches and mb_ereg_replace() will interpret additional syntax. See Named Captures for more information.

MySQL Improved Extension

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values.

MySQL Functions (PDO_MYSQL)

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values. Please note that this only affects the usage of PDO_MYSQL with emulated prepares turned off (e.g. using the native preparation functionality). Statements using connections having PDO::ATTR_EMULATE_PREPARES=true (which is the default) were not affected by the bug fixed and have already been getting the proper fractional seconds values from the engine.

Reflection

Reflection export to string now uses int and bool instead of integer and boolean, respectively.

Standard PHP Library (SPL)

If an SPL autoloader throws an exception, following autoloaders will not be executed. Previously all autoloaders were executed and exceptions were chained.

SimpleXML

Mathematic operations involving SimpleXML objects will now treat the text as an int or float, whichever is more appropriate. Previously values were treated as ints unconditionally.

Incoming Cookies

As of PHP 7.3.23, the names of incoming cookies are no longer url-decoded for security reasons.

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.


Deprecated Features

PHP Core

Case-Insensitive Constants

The declaration of case-insensitive constants has been deprecated. Passing true as the third argument to define() will now generate a deprecation warning. The use of case-insensitive constants with a case that differs from the declaration is also deprecated.

Namespaced assert()

Declaring a function called assert() inside a namespace is deprecated. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Searching Strings for non-string Needle

Passing a non-string needle to string search functions is deprecated. In the future the needle will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, you should either explicitly cast the needle to string or perform an explicit call to chr(). The following functions are affected:

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

The fgetss() function and the string.strip_tags stream filter have been deprecated. This also affects the SplFileObject::fgetss() method and gzgetss() function.

Data Filtering

The explicit usage of the constants FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED is now deprecated; both are implied for FILTER_VALIDATE_URL anyway.

Image Processing and GD

image2wbmp() has been deprecated.

Internationalization Functions

Usage of the Normalizer::NONE form throws a deprecation warning, if PHP is linked with ICU ≥ 56.

Multibyte String

The following undocumented mbereg_*() aliases have been deprecated. Use the corresponding mb_ereg_*() variants instead.

  • 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 and DB2 Functions (PDO_ODBC)

The pdo_odbc.db2_instance_name ini setting has been formally deprecated. It is deprecated in the documentation as of PHP 5.1.1.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

PHP Core

Set(raw)cookie accepts $option Argument

setcookie() and setrawcookie() now also support the following signature:

setcookie(string $name, string $value = "", array $options = []): bool
where $options is an associative array which may have any of the keys "expires", "path", "domain", "secure", "httponly" and "samesite".

New Syslog ini Directives

The following ini Directives have been added to customize logging, if error_log is set to syslog:

syslog.facility
Specifies what type of program is logging the message.
syslog.filter
Specifies the filter type to filter the logged messages, with the supported filter types - all, no-ctrl and ascii. Starting with PHP 7.3.8, raw is also available, restoring the way syslog behaved in previous PHP versions. This filter will also affect calls to syslog().
syslog.ident
Specifies the ident string which is prepended to every message.

Garbage Collection

The cyclic GC has been enhanced, which may result in considerable performance improvements.

Miscellaneous

var_export() now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState().

debug_zval_dump() was changed to display recursive arrays and objects in the same way as var_dump(). Now, it doesn't display them twice.

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

Interactive PHP Debugger

The unused constants PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO and PHPDBG_FUNC have been removed.

FastCGI Process Manager

The getallheaders() function is now also available.

Client URL Library

libcurl ≥ 7.15.5 is now required.

Data Filtering

FILTER_VALIDATE_FLOAT now also supports a thousand option, which defines the set of allowed thousand separator chars. The default ("',.") is fully backward compatible with former PHP versions.

FILTER_SANITIZE_ADD_SLASHES has been added as an alias of the magic_quotes filter (FILTER_SANITIZE_MAGIC_QUOTES). The magic_quotes filter is subject to removal in future versions of PHP.

FTP

The default transfer mode has been changed to binary.

Internationalization Functions

Normalizer::NONE is deprecated, when PHP is linked with ICU ≥ 56.

Introduced Normalizer::FORM_KC_CF as Normalizer::normalize() argument for NFKC_Casefold normalization; available when linked with ICU ≥ 56.

JavaScript Object Notation

A new flag has been added, JSON_THROW_ON_ERROR, which can be used with json_decode() or json_encode() and causes these functions to throw the new JsonException upon an error, instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR.

Multibyte String

The configuration option --with-libmbfl is no longer available.

ODBC (Unified)

Support for ODBCRouter and Birdstep including the birdstep.max_links ini directive has been removed.

OPcache

The opcache.inherited_hack ini directive has been removed. The value has already been ignored since PHP 5.3.0.

OpenSSL

The min_proto_version and max_proto_version ssl stream options as well as related constants for possible TLS protocol values have been added.

Regular Expressions (Perl-Compatible)

The PCRE extension has been upgraded to PCRE2, which may cause minor behavioral changes (for instance, character ranges in classes are now more strictly interpreted), and augments the existing regular expression syntax.

preg_quote() now also escapes the '#' character.

Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

The attribute PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS to enable automatic skipping of empty rowsets has been added.

The PDO::DBLIB_ATTR_TDS_VERSION attribute which exposes the TDS version has been added.

DATETIME2 columns are now treated like DATETIME columns.

SQLite Functions (PDO_SQLITE)

SQLite3 databases can now be opened in read-only mode by setting the new PDO::SQLITE_ATTR_OPEN_FLAGS attribute to PDO::SQLITE_OPEN_READONLY.

Session Handling

session_set_cookie_params() now also supports the following signature:

session_set_cookie_params(array $options): bool
where $options is an associative array which may have any of the keys "lifetime", "path", "domain", "secure", "httponly" and "samesite". Accordingly, the return value of session_get_cookie_params() now also has an element with the key "samesite". Furthermore, the new session.cookie_samesite ini option to set the default of the SameSite directive for cookies has been added. It defaults to "" (empty string), so no SameSite directive is set. Can be set to "Lax" or "Strict", which sets the respective SameSite directive.

Tidy

Building against » tidyp is now also supported transparently. Since tidyp offers no API to get the release date, tidy_get_release() and tidy::getRelease() return 'unknown' in this case.

XML Parser

The return value of the xml_set_external_entity_ref_handler() callback is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.

Zip

Building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration.

Zlib Compression

The zlib/level context option for the compress.zlib wrapper to facilitate setting the desired compression level has been added.

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

PHP Core

More POSIX Conforming File Deletion

File descriptors are opened in shared read/write/delete mode by default. This effectively maps the POSIX semantics and allows to delete files with handles in use. It is not 100% same, some platform differences still persist. After the deletion, the filename entry is blocked, until all the opened handles to it are closed.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 7.1.x to PHP 7.2.x

Table of Contents

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.2.x
  • Other changes

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x and 7.1.x.

User Contributed Notes

There are no user contributed notes for this page.


New features

New object type

A new type, object, has been introduced that can be used for (contravariant) parameter typing and (covariant) return typing of any objects.

<?php

function test(object $obj) : object
{
return new SplQueue();
}

test(new stdClass());

Extension loading by name

Shared extensions no longer require their file extension (.so for Unix or .dll for Windows) to be specified. This is enabled in the php.ini file, as well as in the dl() function.

Abstract method overriding

Abstract methods can now be overridden when an abstract class extends another abstract class.

<?php

abstract class A
{
abstract function test(string $s);
}
abstract class B extends A
{
// overridden - still maintaining contravariance for parameters and covariance for return
abstract function test($s) : int;
}

Sodium is now a core extension

The modern Sodium cryptography library has now become a core extension in PHP.

For a complete function reference, see the Sodium chapter.

Password hashing with Argon2

Argon2 has been added to the password hashing API, where the following constants have been exposed:

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

Extended string types for PDO

PDO's string type has been extended to support the national character type when emulating prepares. This has been done with the following constants:

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

These constants are utilised by bitwise OR'ing them with PDO::PARAM_STR:

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

Additional emulated prepares debugging information for PDO

The PDOStatement::debugDumpParams() method has been updated to include the SQL being sent to the DB, where the full, raw query (including the replaced placeholders with their bounded values) will be shown. This has been added to aid with debugging emulated prepares (and so it will only be available when emulated prepares are turned on).

Support for extended operations in LDAP

Support for EXOP has been added to the LDAP extension. This has been done by exposing the following functions and constants:

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()
  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

Address Information additions to the Sockets extension

The sockets extension now has the ability to lookup address information, as well as connect to it, bind to it, and explain it. The following four functions have been added for this:

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Parameter type widening

Parameter types from overridden methods and from interface implementations may now be omitted. This is still in compliance with LSP, since parameters types are contravariant.

<?php

interface A
{
public function Test(array $input);
}

class B implements A
{
public function Test($input){} // type omitted for $input
}

Allow a trailing comma for grouped namespaces

A trailing comma can now be added to the group-use syntax introduced in PHP 7.0.

<?php

use Foo\Bar\{
Foo,
Bar,
Baz,
};

proc_nice() support on Windows

The proc_nice() function is now supported on Windows.

pack() and unpack() endian support

The pack() and unpack() functions now support float and double in both little and big endian.

Enhancements to the EXIF extension

The EXIF extension has been updated to support a much larger range of formats. This means that their format specific tags are now properly translated when parsing images with the exif_read_data() function. The following new formats are now supported:

  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

The EXIF functions exif_read_data() and exif_thumbnail() now support passing streams as their first argument.

New features in PCRE

  • The J modifier for setting PCRE_DUPNAMES has been added.

SQLite3 allows writing BLOBs

SQLite3::openBlob() now allows to open BLOB fields in write mode; formerly only read mode was supported.

Oracle OCI8 Transparent Application Failover Callbacks

Support for Oracle Database Transparent Application Failover (TAF) callbacks has been added. TAF allows PHP OCI8 applications to automatically reconnect to a preconfigured database when a connection is broken. The new TAF callback support allows PHP applications to monitor and control reconnection during failover.

Enhancements to the ZIP extension

Read and write support for encrypted archives has been added (requires libzip 1.2.0).

The ZipArchive class now implements the Countable interface.

The zip:// stream now accepts a 'password' context option.

User Contributed Notes

antonfedonyuk at gmail dot com 21-Apr-2021 12:27
Note: "omitted" = "removed":
<?php
declare(strict_types=1);

interface ITest
{
    public function run(array $input);
}

class Test implements ITest
{
    public function run($input) {
       return $input;
   }
}

echo (new Test())->run('foo'); // display foo, no error
?>
info at ensostudio dot ru 11-Sep-2020 07:28
Note: you cant change parameter type for abstract method defined in interface.
<?php
abstract class AbstractAssocArray imlements ArrayAccess
{
    abstract public function offsetSet($offset, $value): void;
    ...
}
abstract class AbstractAssocArray2 extends AbstractAssocArray
{
    abstract public function offsetSet(string $offset, $value): void;
}
class AssocArray extends AbstractAssocArray2
{
    public function offsetSet(string $offset, $value): void
    {
         $this->{$offset} = $value;
    }
}
?>
It's throw fatal error: Declaration of AbstractAssocArray::offsetSet(string $offset, $value): void must be compatible with AbstractAssocArrayAccess::offsetSet($offset, $value).


New functions

PHP Core

  • stream_isatty()
  • sapi_windows_vt100_support()

SPL

  • spl_object_id()

DOM

  • DomNodeList::count()
  • DOMNamedNodeMap::count()

FTP

  • ftp_append()

GD

  • imagesetclip()
  • imagegetclip()
  • imageopenpolygon()
  • imageresolution()
  • imagecreatefrombmp()
  • imagebmp()

Hash

  • hash_hmac_algos()

LDAP

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()

Multibyte String

  • mb_chr()
  • mb_ord()
  • mb_scrub()

Oracle OCI8

  • oci_register_taf_callback()
  • oci_unregister_taf_callback()

Sockets

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Sodium

  • sodium_add()
  • sodium_bin2hex()
  • sodium_compare()
  • sodium_crypto_aead_aes256gcm_decrypt()
  • sodium_crypto_aead_aes256gcm_encrypt()
  • sodium_crypto_aead_aes256gcm_is_available()
  • sodium_crypto_aead_aes256gcm_keygen()
  • sodium_crypto_aead_chacha20poly1305_decrypt()
  • sodium_crypto_aead_chacha20poly1305_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen()
  • sodium_crypto_aead_chacha20poly1305_keygen()
  • sodium_crypto_auth_keygen()
  • sodium_crypto_auth_verify()
  • sodium_crypto_auth()
  • sodium_crypto_box_keypair_from_secretkey_and_publickey()
  • sodium_crypto_box_keypair()
  • sodium_crypto_box_open()
  • sodium_crypto_box_publickey_from_secretkey()
  • sodium_crypto_box_publickey()
  • sodium_crypto_box_seal_open()
  • sodium_crypto_box_seal()
  • sodium_crypto_box_secretkey()
  • sodium_crypto_box_seed_keypair()
  • sodium_crypto_box()
  • sodium_crypto_generichash_final()
  • sodium_crypto_generichash_init()
  • sodium_crypto_generichash_keygen()
  • sodium_crypto_generichash_update()
  • sodium_crypto_generichash()
  • sodium_crypto_kdf_derive_from_key()
  • sodium_crypto_kdf_keygen()
  • sodium_crypto_kx_client_session_keys()
  • sodium_crypto_kx_keypair()
  • sodium_crypto_kx_publickey()
  • sodium_crypto_kx_secretkey()
  • sodium_crypto_kx_seed_keypair()
  • sodium_crypto_kx_server_session_keys()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str()
  • sodium_crypto_pwhash_scryptsalsa208sha256()
  • sodium_crypto_pwhash_str_verify()
  • sodium_crypto_pwhash_str()
  • sodium_crypto_pwhash()
  • sodium_crypto_scalarmult_base()
  • sodium_crypto_scalarmult()
  • sodium_crypto_secretbox_keygen()
  • sodium_crypto_secretbox_open()
  • sodium_crypto_secretbox()
  • sodium_crypto_shorthash_keygen()
  • sodium_crypto_shorthash()
  • sodium_crypto_sign_detached()
  • sodium_crypto_sign_ed25519_pk_to_curve25519()
  • sodium_crypto_sign_ed25519_sk_to_curve25519()
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey()
  • sodium_crypto_sign_keypair()
  • sodium_crypto_sign_open()
  • sodium_crypto_sign_publickey_from_secretkey()
  • sodium_crypto_sign_publickey()
  • sodium_crypto_sign_secretkey()
  • sodium_crypto_sign_seed_keypair()
  • sodium_crypto_sign_verify_detached()
  • sodium_crypto_sign()
  • sodium_crypto_stream_keygen()
  • sodium_crypto_stream_xor()
  • sodium_crypto_stream()
  • sodium_hex2bin()
  • sodium_increment()
  • sodium_memcmp()
  • sodium_memzero()
  • sodium_pad()
  • sodium_unpad()

ZIP

  • ZipArchive::count()
  • ZipArchive::setEncryptionName()
  • ZipArchive::setEncryptionIndex()

User Contributed Notes

There are no user contributed notes for this page.


New global constants

PHP Core

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

File Information

  • FILEINFO_EXTENSION

JSON

  • JSON_INVALID_UTF8_IGNORE
  • JSON_INVALID_UTF8_SUBSTITUTE

GD

  • IMG_EFFECT_MULTIPLY
  • IMG_BMP

LDAP

  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

Password Hashing

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

PCRE

  • PREG_UNMATCHED_AS_NULL

PDO

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

Sodium

  • SODIUM_LIBRARY_VERSION
  • SODIUM_LIBRARY_MAJOR_VERSION
  • SODIUM_LIBRARY_MINOR_VERSION
  • SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES
  • SODIUM_CRYPTO_AUTH_BYTES
  • SODIUM_CRYPTO_AUTH_KEYBYTES
  • SODIUM_CRYPTO_BOX_SEALBYTES
  • SODIUM_CRYPTO_BOX_SECRETKEYBYTES
  • SODIUM_CRYPTO_BOX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_BOX_KEYPAIRBYTES
  • SODIUM_CRYPTO_BOX_MACBYTES
  • SODIUM_CRYPTO_BOX_NONCEBYTES
  • SODIUM_CRYPTO_BOX_SEEDBYTES
  • SODIUM_CRYPTO_KDF_BYTES_MIN
  • SODIUM_CRYPTO_KDF_BYTES_MAX
  • SODIUM_CRYPTO_KDF_CONTEXTBYTES
  • SODIUM_CRYPTO_KDF_KEYBYTES
  • SODIUM_CRYPTO_KX_SEEDBYTES
  • SODIUM_CRYPTO_KX_SESSIONKEYBYTES
  • SODIUM_CRYPTO_KX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_KX_SECRETKEYBYTES
  • SODIUM_CRYPTO_KX_KEYPAIRBYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MAX
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX
  • SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
  • SODIUM_CRYPTO_PWHASH_ALG_DEFAULT
  • SODIUM_CRYPTO_PWHASH_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_SCALARMULT_BYTES
  • SODIUM_CRYPTO_SCALARMULT_SCALARBYTES
  • SODIUM_CRYPTO_SHORTHASH_BYTES
  • SODIUM_CRYPTO_SHORTHASH_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_MACBYTES
  • SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
  • SODIUM_CRYPTO_SIGN_BYTES
  • SODIUM_CRYPTO_SIGN_SEEDBYTES
  • SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
  • SODIUM_CRYPTO_SIGN_SECRETKEYBYTES
  • SODIUM_CRYPTO_SIGN_KEYPAIRBYTES
  • SODIUM_CRYPTO_STREAM_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_KEYBYTES

Zip

  • ZipArchive::EM_NONE
  • ZipArchive::EM_AES_128
  • ZipArchive::EM_AES_192
  • ZipArchive::EM_AES_256

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Prevent number_format() from returning negative zero

Previously, it was possible for the number_format() function to return -0. Whilst this is perfectly valid according to the IEEE 754 floating point specification, this oddity was not desirable for displaying formatted numbers in a human-readable form.

<?php

var_dump(number_format(-0.01)); // now outputs string(1) "0" instead of string(2) "-0"

Convert numeric keys in object and array casts

Numeric keys are now better handled when casting arrays to objects and objects to arrays (either from explicit casting or by settype()).

This means that integer (or stringy integer) keys from arrays being casted to objects are now accessible:

<?php

// array to object
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
$obj,
$obj->{'0'}, // now accessible
$obj->{0} // now accessible
);

The above example will output:

object(stdClass)#1 (1) {
  ["0"]=>    // string key now, rather than integer key
  int(1)
}
int(1)
int(1)

And integer (or stringy integer) keys from objects being casted to arrays are now accessible:

<?php

// object to array
$obj = new class {
public function __construct()
{
$this->{0} = 1;
}
};
$arr = (array)$obj;
var_dump(
$arr,
$arr[0], // now accessible
$arr['0'] // now accessible
);

The above example will output:

array(1) {
  [0]=>    // integer key now, rather than string key
  int(1)
}
int(1)
int(1)

Disallow passing null to get_class()

Previously, passing null to the get_class() function would output the name of the enclosing class. This behaviour has now been removed, where an E_WARNING will be output instead. To achieve the same behaviour as before, the argument should simply be omitted.

Warn when counting non-countable types

An E_WARNING will now be emitted when attempting to count() non-countable types (this includes the sizeof() alias function).

<?php

var_dump(
count(null), // NULL is not countable
count(1), // integers are not countable
count('abc'), // strings are not countable
count(new stdClass), // objects not implementing the Countable interface are not countable
count([1,2]) // arrays are countable
);

The above example will output:

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d
int(0)
int(1)
int(1)
int(1)
int(2)

Move ext/hash from resources to objects

As part of the long-term migration away from resources, the Hash extension has been updated to use objects instead of resources. The change should be seamless for PHP developers, except for where is_resource() checks have been made (which will need updating to is_object() instead).

Improve SSL/TLS defaults

The following changes to the defaults have been made:

  • tls:// now defaults to TLSv1.0 or TLSv1.1 or TLSv1.2
  • ssl:// an alias of tls://
  • STREAM_CRYPTO_METHOD_TLS_* constants default to TLSv1.0 or TLSv1.1 + TLSv1.2, instead of TLSv1.0 only

gettype() return value on closed resources

Previously, using gettype() on a closed resource would return a string of "unknown type". Now, a string of "resource (closed)" will be returned.

is_object() and __PHP_Incomplete_Class

Previously, using is_object() on the __PHP_Incomplete_Class class would return false. Now, true will be returned.

Promote the error level of undefined constants

Unqualified references to undefined constants will now generate an E_WARNING (instead of an E_NOTICE). In the next major version of PHP, they will generate Error exceptions.

Windows support

The officially supported, minimum Windows versions are now Windows 7/Server 2008 R2.

Checks on default property values of traits

Compatibility checks upon default trait property values will no longer perform casting.

object for class names

The object name was previously soft-reserved in PHP 7.0. This is now hard-reserved, prohibiting it from being used as a class, trait, or interface name.

NetWare support

Support for NetWare has now been removed.

array_unique() with SORT_STRING

While array_unique() with SORT_STRING formerly copied the array and removed non-unique elements (without packing the array afterwards), now a new array is built by adding the unique elements. This can result in different numeric indexes.

bcmod() changes with floats

The bcmod() function no longer truncates fractional numbers to integers. As such, its behavior now follows fmod(), rather than the % operator. For example bcmod('4', '3.5') now returns 0.5 instead of 1.

Hashing functions and non-cryptographic hashes

The hash_hmac(), hash_hmac_file(), hash_pbkdf2(), and hash_init() (with HASH_HMAC) functions no longer accept non-cryptographic hashes.

json_decode() function options

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is null. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

rand() and mt_rand() output

Sequences generated by rand() and mt_rand() for a specific seed may differ from PHP 7.1 on 64-bit machines (due to the fixing of a modulo bias bug in the implementation).

Removal of sql.safe_mode ini setting

The sql.safe_mode ini setting has now been removed.

Changes to date_parse() and date_parse_from_format()

The zone element of the array returned by date_parse() and date_parse_from_format() represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

Incoming Cookies

As of PHP 7.2.34, the names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated features in PHP 7.2.x

Unquoted strings

Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.

<?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() and jpeg2wbmp()

The png2wbmp() and jpeg2wbmp() functions from the GD extension have now been deprecated and will be removed in the next major version of PHP.

INTL_IDNA_VARIANT_2003 variant

The Intl extension has deprecated the INTL_IDNA_VARIANT_2003 variant, which is currently being used as the default for idn_to_ascii() and idn_to_utf8(). PHP 7.4 will see these defaults changed to INTL_IDNA_VARIANT_UTS46, and the next major version of PHP will remove INTL_IDNA_VARIANT_2003 altogether.

__autoload() method

The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.

track_errors ini setting and $php_errormsg variable

When the track_errors ini setting is enabled, a $php_errormsg variable is created in the local scope when a non-fatal error occurs. Given that the preferred way of retrieving such error information is by using error_get_last(), this feature has been deprecated.

create_function() function

Given the security issues of this function (being a thin wrapper around eval()), this dated function has now been deprecated. The preferred alternative is to use anonymous functions.

mbstring.func_overload ini setting

Given the interoperability problems of string-based functions being used in environments with this setting enabled, it has now been deprecated.

(unset) cast

Casting any expression to this type will always result in null, and so this superfluous casting type has now been deprecated.

parse_str() without a second argument

Without the second argument to parse_str(), the query string parameters would populate the local symbol table. Given the security implications of this, using parse_str() without a second argument has now been deprecated. The function should always be used with two arguments, as the second argument causes the query string to be parsed into an array.

gmp_random() function

This function generates a random number based upon a range that is calculated by an unexposed, platform-specific limb size. Because of this, the function has now been deprecated. The preferred way of generating a random number using the GMP extension is by gmp_random_bits() and gmp_random_range().

each() function

This function is far slower at iteration than a normal foreach, and causes implementation issues for some language changes. It has therefore been deprecated.

assert() with a string argument

Using assert() with a string argument required the string to be eval()'ed. Given the potential for remote code execution, using assert() with a string argument has now been deprecated in favour of using boolean expressions.

$errcontext argument of error handlers

The $errcontext argument contains all local variables of the error site. Given its rare usage, and the problems it causes with internal optimisations, it has now been deprecated. Instead, a debugger should be used to retrieve information on local variables at the error site.

read_exif_data() function

The read_exif_data() alias has been deprecated. The exif_read_data() function should be used instead.

User Contributed Notes

Anonymous 26-Jul-2018 05:09
An empty <?php?> Codeblock in PHP 7.2.0 will put out an "Unquoted strings" warning. To prevent that, add at least one empty space into the codeblock.

Example:
<?php

<?php/*
echo "This was some useful code.\n";
*/?>

?>
Gives: PHP Warning:  Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP)

Fix via:
<?php

<?php   /*
echo "This was some useful code.\";
*/?>

?>

Don't know if that is an intentional behaviour or a side effect.
webmaster at thedigitalorchard dot ca 01-Feb-2018 05:14
Instead of __autoload(), you can use spl_autoload_register() very easily, as per the documentation:

spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

And this lets you have multiple autoloaders instead of one global one.


Other changes

Moving of utf8_encode() and utf8_decode()

The utf8_encode() and utf8_decode() functions have now been moved to the standard extension as string functions, whereas before the XML extension was required for them to be available.

Changes to mail() and mb_send_mail()

The $additional_headers parameter of mail() and mb_send_mail() now also accepts an array instead of a string.

LMDB support

The DBA extension now has support for LMDB.

Changes to the PHP build system

  • Unix: Autoconf 2.64 or greater is now required to build PHP.
  • Unix: --with-pdo-oci configure argument no longer needs the version number of the Oracle Instant Client.
  • Unix: --enable-gd-native-ttf configure argument has been removed. This was not used since PHP 5.5.0.
  • Windows: --with-config-profile configure argument has been added. This can be used to save specific configures, much like the magical config.nice.bat file.

Changes to GD

  • imageantialias() is now also available if compiled with a system libgd.
  • imagegd() stores truecolor images as real truecolor images. Formerly, they have been converted to palette.

Moving MCrypt to PECL

The MCrypt extension has now been moved out of the core to PECL. Given the mcrypt library has not seen any updates since 2007, its usage is highly discouraged. Instead, either the OpenSSL or Sodium extension should be used.

session_module_name()

Passing "user" to session_module_name() now raises an error of level E_RECOVERABLE_ERROR. Formerly, this has been silently ignored.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 7.0.x to PHP 7.1.x

Table of Contents

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.1.x
  • Changed functions
  • Other changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x.

User Contributed Notes

There are no user contributed notes for this page.


New features

Nullable types

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, null can be passed as an argument, or returned as a value, respectively.

<?php

function testReturn(): ?string
{
return 'elePHPant';
}

var_dump(testReturn());

function testReturn(): ?string
{
return null;
}

var_dump(testReturn());

function test(?string $name)
{
var_dump($name);
}

test('elePHPant');
test(null);
test();

The above example will output:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void functions

A void return type has been introduced. Functions declared with void as their return type must either omit their return statement altogether, or use an empty return statement. null is not a valid return value for a void function.

<?php
function swap(&$left, &$right): void
{
if ($left === $right) {
return;
}

$tmp = $left;
$left = $right;
$right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

The above example will output:

null
int(2)
int(1)

Attempting to use a void function's return value simply evaluates to null, with no warnings emitted. The reason for this is because warnings would implicate the use of generic higher order functions.

Symmetric array destructuring

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

<?php
$data = [
[1, 'Tom'],
[2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0];

// list() style
foreach ($data as list($id, $name)) {
// logic here with $id and $name
}

// [] style
foreach ($data as [$id, $name]) {
// logic here with $id and $name
}

Class constant visibility

Support for specifying the visibility of class constants has been added.

<?php
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}

iterable pseudo-type

A new pseudo-type (similar to callable) called iterable has been introduced. It may be used in parameter and return types, where it accepts either arrays or objects that implement the Traversable interface. With respect to subtyping, parameter types of child classes may broaden a parent's declaration of array or Traversable to iterable. With return types, child classes may narrow a parent's return type of iterable to array or an object that implements Traversable.

<?php
function iterator(iterable $iter)
{
foreach ($iter as $val) {
//
}
}

Multi catch exception handling

Multiple exceptions per catch block may now be specified using the pipe character (|). This is useful for when different exceptions from different class hierarchies are handled the same.

<?php
try {
// some code
} catch (FirstException | SecondException $e) {
// handle first and second exceptions
}

Support for keys in list()

You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
// logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
// logic here with $id and $name
}

Support for negative string offsets

Support for negative string offsets has been added to the string manipulation functions accepting offsets, as well as to string indexing with [] or {}. In such cases, a negative offset is interpreted as being an offset from the end of the string.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

The above example will output:

string (1) "e"
int(3)

Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

The above example will output:

The last character of 'bar' is 'r'.

Support for AEAD in ext/openssl

Support for AEAD (modes GCM and CCM) have been added by extending the openssl_encrypt() and openssl_decrypt() functions with additional parameters.

Convert callables to Closures with Closure::fromCallable()

A new static method has been introduced to the Closure class to allow for callables to be easily converted into Closure objects.

<?php
class Test
{
public function exposeFunction()
{
return Closure::fromCallable([$this, 'privateFunction']);
}

private function privateFunction($param)
{
var_dump($param);
}
}

$privFunc = (new Test)->exposeFunction();
$privFunc('some value');

The above example will output:

string(10) "some value"

Asynchronous signal handling

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP, function($sig) {
echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

The above example will output:

SIGHUP

HTTP/2 server push support in ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUSH_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.

Stream Context Options

The tcp_nodelay stream context option has been added.

User Contributed Notes

DYM 09-Apr-2018 10:36
<?php
function swap( &$a, &$b ): void
  { [ $a, $b ] = [ $b, $a ]; }
?>
unti1x 06-Apr-2018 11:20
Note that declaring nullable return type does not mean that you can skip return statement at all. For example:

php > function a(): ?string { }
php > a();
PHP Warning:  Uncaught TypeError: Return value of a() must be of the type string or null, none returned in php shell code:2

php > function b(): ?string { return; }
PHP Fatal error:  A function with return type must return a value (did you mean "return null;" instead of "return;"?) in php shell code on line 2


New functions

PHP Core

  • sapi_windows_cp_get()
  • sapi_windows_cp_set()
  • sapi_windows_cp_conv()
  • sapi_windows_cp_is_utf8()

Closure

  • Closure::fromCallable()

CURL

  • curl_multi_errno()
  • curl_share_errno()
  • curl_share_strerror()

OpenSSL

  • openssl_get_curve_names()

Session

  • session_create_id()
  • session_gc()

SPL

  • is_iterable()

PCNTL

  • pcntl_async_signals()
  • pcntl_signal_get_handler()

User Contributed Notes

There are no user contributed notes for this page.


New global constants

Core Predefined Constants

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing and GD

  • IMAGETYPE_WEBP

JSON

  • JSON_UNESCAPED_LINE_TERMINATORS

LDAP

  • LDAP_OPT_X_SASL_NOCANON
  • LDAP_OPT_X_SASL_USERNAME
  • LDAP_OPT_X_TLS_CACERTDIR
  • LDAP_OPT_X_TLS_CACERTFILE
  • LDAP_OPT_X_TLS_CERTFILE
  • LDAP_OPT_X_TLS_CIPHER_SUITE
  • LDAP_OPT_X_TLS_KEYFILE
  • LDAP_OPT_X_TLS_RANDOM_FILE
  • LDAP_OPT_X_TLS_CRLCHECK
  • LDAP_OPT_X_TLS_CRL_NONE
  • LDAP_OPT_X_TLS_CRL_PEER
  • LDAP_OPT_X_TLS_CRL_ALL
  • LDAP_OPT_X_TLS_DHFILE
  • LDAP_OPT_X_TLS_CRLFILE
  • LDAP_OPT_X_TLS_PROTOCOL_MIN
  • LDAP_OPT_X_TLS_PROTOCOL_SSL2
  • LDAP_OPT_X_TLS_PROTOCOL_SSL3
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_0
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_1
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
  • LDAP_OPT_X_TLS_PACKAGE
  • LDAP_OPT_X_KEEPALIVE_IDLE
  • LDAP_OPT_X_KEEPALIVE_PROBES
  • LDAP_OPT_X_KEEPALIVE_INTERVAL

PostgreSQL

  • PGSQL_NOTICE_LAST
  • PGSQL_NOTICE_ALL
  • PGSQL_NOTICE_CLEAR

SPL

  • MT_RAND_PHP

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

<?php
function test($param){}
test();

The above example will output something similar to:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Forbid dynamic calls to scope introspection functions

Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • assert() - with a string as the first argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - with one arg
  • parse_str() - with one arg
<?php
(function () {
$func = 'func_num_args';
$func();
})();

The above example will output:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Invalid class, interface, and trait names

The following names cannot be used to name classes, interfaces, or traits:

  • void
  • iterable

Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

Fixes to mt_rand() algorithm

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_rand() was relied upon, then MT_RAND_PHP can be used as optional second parameter to mt_srand() to preserve the old (incorrect) implementation.

rand() aliased to mt_rand() and srand() aliased to mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changed: rand(), shuffle(), str_shuffle(), and array_rand().

Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

error_log changes with syslog value

If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

Do not call destructors on incomplete objects

Destructors are now never called for objects that throw an exception during the execution of their constructor. In previous versions this behavior depended on whether the object was referenced outside the constructor (e.g. by an exception backtrace).

call_user_func() handling of reference arguments

call_user_func() will now always generate a warning upon calls to functions that expect references as arguments. Previously this depended on whether the call was fully qualified.

Additionally, call_user_func() and call_user_func_array() will no longer abort the function call in this case. The "expected reference" warning will be emitted, but the call will proceed as usual.

The empty index operator is not supported for strings anymore

Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

Assignment via string index access on an empty string

String modification by character on an empty string now works like for non-empty strings, i.e. writing to an out of range offset pads the string with spaces, where non-integer types are converted to integer, and only the first character of the assigned string is used. Formerly, empty strings where silently treated like an empty array.

<?php
$a = '';
$a[10] = 'foo';
var_dump($a);
?>

Output of the above example in PHP 7.0:

array(1) {
  [10]=>
  string(3) "foo"
}

Output of the above example in PHP 7.1:

string(11) "          f"

Removed ini directives

The following ini directives have been removed:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Output of the above example in PHP 7.0:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Output of the above example in PHP 7.1:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Note:

Don't rely on the order of elements which compare as equal; it might change anytime.

Error message for E_RECOVERABLE errors

The error message for E_RECOVERABLE errors has been changed from "Catchable fatal error" to "Recoverable fatal error".

$options parameter of unserialize()

The allowed_classes element of the $options parameter of unserialize() is now strictly typed, i.e. if anything other than an array or a bool is given, unserialize() returns false and issues an E_WARNING.

DateTime constructor incorporates microseconds

DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return false instead of true:

<?php
new DateTime() == new DateTime();
?>

Fatal errors to Error exceptions conversions

In the Date extension, invalid serialization data for DateTime or DatePeriod classes, or timezone initialization failure from serialized data, will now throw an Error exception from the __wakeup() or __set_state() methods, instead of resulting in a fatal error.

In the DBA extension, data modification functions (such as dba_insert()) will now throw an Error exception instead of triggering a catchable fatal error if the key does not contain exactly two elements.

In the DOM extension, invalid schema or RelaxNG validation contexts will now throw an Error exception instead of resulting in a fatal error. Similarly, attempting to register a node class that does not extend the appropriate base class, or attempting to read an invalid property or write to a readonly property, will also now throw an Error exception.

In the IMAP extension, email addresses longer than 16385 bytes will throw an Error exception instead of resulting in a fatal error.

In the Intl extension, failing to call the parent constructor in a class extending Collator before invoking the parent methods will now throw an Error instead of resulting in a recoverable fatal error. Also, cloning a Transliterator object will now throw an Error exception on failure to clone the internal transliterator instead of resulting in a fatal error.

In the LDAP extension, providing an unknown modification type to ldap_batch_modify() will now throw an Error exception instead of resulting in a fatal error.

In the mbstring extension, the mb_ereg() and mb_eregi() functions will now throw a ParseError exception if an invalid PHP expression is provided and the 'e' option is used.

In the Mcrypt extension, the mcrypt_encrypt() and mcrypt_decrypt() will now throw an Error exception instead of resulting in a fatal error if mcrypt cannot be initialized.

In the mysqli extension, attempting to read an invalid property or write to a readonly property will now throw an Error exception instead of resulting in a fatal error.

In the Reflection extension, failing to retrieve a reflection object or retrieve an object property will now throw an Error exception instead of resulting in a fatal error.

In the Session extension, custom session handlers that do not return strings for session IDs will now throw an Error exception instead of resulting in a fatal error when a function is called that must generate a session ID.

In the SimpleXML extension, creating an unnamed or duplicate attribute will now throw an Error exception instead of resulting in a fatal error.

In the SPL extension, attempting to clone an SplDirectory object will now throw an Error exception instead of resulting in a fatal error. Similarly, calling ArrayIterator::append() when iterating over an object will also now throw an Error exception.

In the standard extension, the assert() function, when provided with a string argument as its first parameter, will now throw a ParseError exception instead of resulting in a catchable fatal error if the PHP code is invalid. Similarly, calling forward_static_call() outside of a class scope will now throw an Error exception.

In the Tidy extension, creating a tidyNode manually will now throw an Error exception instead of resulting in a fatal error.

In the WDDX extension, a circular reference when serializing will now throw an Error exception instead of resulting in a fatal error.

In the XML-RPC extension, a circular reference when serializing will now throw an instance of Error exception instead of resulting in a fatal error.

In the Zip extension, the ZipArchive::addGlob() method will now throw an Error exception instead of resulting in a fatal error if glob support is not available.

Lexically bound variables cannot reuse names

Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter. For example, all of these function definition will result in a fatal error:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

long2ip() parameter type change

long2ip() now expects an int instead of a string.

JSON encoding and decoding

The serialize_precision ini setting now controls the serialization precision when encoding floats.

Decoding an empty key now results in an empty property name, rather than _empty_ as a property name.

<?php
var_dump(json_decode(json_encode(['' => 1])));

The above example will output something similar to:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

When supplying the JSON_UNESCAPED_UNICODE flag to json_encode(), the sequences U+2028 and U+2029 are now escaped.

Changes to mb_ereg() and mb_eregi() parameter semantics

The third parameter to the mb_ereg() and mb_eregi() functions (regs) will now be set to an empty array if nothing was matched. Formerly, the parameter would not have been modified.

Drop support for the sslv2 stream

The sslv2 stream has now been dropped in OpenSSL.

Forbid "return;" for typed returns already at compile-time

Return statements without argument in functions which declare a return type now trigger E_COMPILE_ERROR (unless the return type is declared as void), even if the return statement would never be reached.

User Contributed Notes

david at artefactual dot com 04-Apr-2019 05:29
Regarding the ArgumentCountError, PHP 7.1+ does still support user functions with a variable number of arguments, using the "func(...$args) {}" syntax, see: https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
mikem at gmail dot com 21-Nov-2017 12:09
ArgumentCountError - this modification is the main reason to avoid this version on older projects.
kees at twekaers dot net 21-Mar-2017 11:49
The backwards incompatible change 'The empty index operator is not supported for strings anymore' has a lot more implications than just a fatal error on the following code

<?php
$a = "";
$a[] = "hello world";
var_dump($a);
?>

This will give a fatal error in 7.1 but will work as expected in 7.0 or below and give you: (no notice, no warning)

array(1) {
  [0]=>
  string(11) "hello world"
}

However, the following is also changed:

<?php
$a = "";
$a[0] = "hello world";
var_dump($a);
// 7.1: string(1) "h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

$a = "";
$a[5] = "hello world";
var_dump($a);
// 7.1: string(6) "     h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

?>
m dot r dot sopacua at gmail dot com 30-Dec-2016 03:49
"OMFG! Why was session.hash_function removed?!? Dude!"

https://wiki.php.net/rfc/session-id-without-hashing

There. Saved ya a search.
love at sickpeople dot se 24-Nov-2016 07:59
For anyone migrating from 5.x to 7.1:

About "Array ordering when elements are automatically created during by reference assignments has changed" on this page

(http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.array-order)

The behaviour of 7.1 is THE SAME as of PHP 5. It is only 7.0 that differs.

See https://3v4l.org/frbUc

<?php

$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);


Deprecated features in PHP 7.1.x

ext/mcrypt

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Eval option for mb_ereg_replace() and mb_eregi_replace()

The e pattern modifier has been deprecated for the mb_ereg_replace() and mb_eregi_replace() functions.

User Contributed Notes

There are no user contributed notes for this page.


Changed functions

PHP Core

  • getopt() has an optional third parameter that exposes the index of the next element in the argument vector list to be processed. This is done via a by-ref parameter.
  • getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.
  • get_headers() now has an additional parameter to enable for the passing of custom stream contexts.
  • output_reset_rewrite_vars() no longer resets session URL rewrite variables.
  • parse_url() is now more restrictive and supports RFC3986.
  • unpack() now accepts an optional third parameter to specify the offset to begin unpacking from.

File System

  • file_get_contents() now accepts a negative seek offset if the stream is seekable.
  • tempnam() now emits a notice when falling back to the system's temp directory.

JSON

  • json_encode() now accepts a new option, JSON_UNESCAPED_LINE_TERMINATORS, to disable the escaping of U+2028 and U+2029 characters when JSON_UNESCAPED_UNICODE is supplied.

Multibyte String

  • mb_ereg() now rejects illegal byte sequences.
  • mb_ereg_replace() now rejects illegal byte sequences.

PDO

  • PDO::lastInsertId() for PostgreSQL will now trigger an error when nextval has not been called for the current session (the postgres connection).

PostgreSQL

  • pg_last_notice() now accepts an optional parameter to specify an operation. This can be done with one of the following new constants: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, or PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() now accepts an optional second parameter to specify the result type (similar to the third parameter of pg_fetch_array()).
  • pg_select() now accepts an optional fourth parameter to specify the result type (similar to the third parameter of pg_fetch_array()).

Session

  • session_start() now returns false and no longer initializes $_SESSION when it failed to start the session.

User Contributed Notes

There are no user contributed notes for this page.


Other changes

Notices and warnings on arithmetic with invalid strings

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

<?php
'1b' + 'something';

The above example will output:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Warn on octal escape sequence overflow

Previously, 3-octet octal string escape sequences would overflow silently. Now, they will still overflow, but E_WARNING will be emitted.

<?php
var_dump("\500");

The above example will output:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Inconsistency fixes to $this

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

Session ID generation without hashing

Session IDs will no longer be hashed upon generation. With this change brings about the removal of the following four ini settings:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

And the addition of the following two ini settings:

  • session.sid_length - defines the length of the session ID, defaulting to 32 characters for backwards compatibility)
  • session.sid_bits_per_character - defines the number of bits to be stored per character (i.e. increases the range of characters that can be used in the session ID), defaulting to 4 for backwards compatibility

Changes to INI file handling

precision

If the value is set to -1, then the dtoa mode 0 is used. The default value is still 14.

serialize_precision

If the value is set to -1, then the dtoa mode 0 is used. The value -1 is now used by default.

gd.jpeg_ignore_warning

The default of this php.ini setting has been changed to 1, so by default libjpeg warnings are ignored.

opcache.enable_cli

The default of this php.ini setting has been changed to 1 (enabled) in PHP 7.1.2, and back to 0 (disabled) in PHP 7.1.7.

Session ID generation with a CSPRNG only

Session IDs will now only be generated with a CSPRNG.

More informative TypeError messages when null is allowed

TypeError exceptions for arg_info type checks will now provide more informative error messages. If the parameter type or return type accepts null (by either having a default value of null or being a nullable type), then the error message will now mention this with a message of "must be ... or null" or "must ... or be null."

User Contributed Notes

Ta7To7 27-Feb-2018 05:47
Note that using Incrementing/Decrementing operators on string is legal
<?php
$str = "";
echo ++$str; // output: 1
?>


Windows Support

Support for long and UTF-8 path

If a web application is UTF-8 conform, no further action is required. For applications depending on paths in non UTF-8 encodings for I/O, an explicit INI directive has to be set. The encoding INI settings check relies on the order in the core:

  • internal_encoding
  • default_charset
  • zend.multibyte

Several functions for codepage handling were introduced:

  • sapi_windows_cp_set() to set the default codepage
  • sapi_windows_cp_get() to retrieve the current codepage
  • sapi_windows_cp_is_utf8()
  • sapi_windows_cp_conv() to convert between codepages, using iconv() compatible signature

These functions are thread safe.

The console output codepage is adjusted depending on the encoding used in PHP. Depending on the concrete system OEM codepage, the visible output might or might be not correct. For example, in the default cmd.exe and on a system with the OEM codepage 437, outputs in codepages 1251, 1252, 1253 and some others can be shown correctly when using UTF-8. On the same system, chars in codepage like 20932 probably won't be shown correctly. This refers to the particular system rules for codepage, font compatibility and the particular console program used. PHP automatically sets the console codepage according to the encoding rules from php.ini. Using alternative consoles instead of cmd.exe directly might bring better experience in some cases.

Nevertheless be aware, runtime codepage switch after the request start might bring unexpected side effects on CLI. The preferable way is php.ini, When PHP CLI is used in a console emulator, that doesn't support Unicode, it might possibly be required, to avoid changing the console codepage. The best way to achieve it is by setting the default or internal encoding to correspond the ANSI codepage. Another method is to set the INI directives output_encoding and input_encoding to the required codepage, in which case however the difference between internal and I/O codepage is likely to cause mojibake. In rare cases, if PHP happens to crash gracefully, the original console codepage might be not restored. In this case, the chcp command can be used, to restore it manually.

Special awareness for the DBCS systems - the codepage switch on runtime using ini_set() is likely to cause display issues. The difference to the non DBCS systems is, that the extended characters require two console cells to be displayed. In certain case, only the mapping of the characters into the glyph set of the font could happen, no actual font change. This is the nature of DBCS systems, the most simple way to prevent display issues is to avoid usage of ini_set() for the codepage change.

As a result of UTF-8 support in the streams, PHP scripts are not limited to ASCII or ANSI filenames anymore. This is supported out of the box on CLI. For other SAPI, the documentation for the corresponding server is useful.

Long paths support is transparent. Paths longer than 260 bytes get automatically prefixed with \\?\. The max path length is limited to 2048 bytes. Be aware, that the path segment limit (basename length) still persists.

For the best portability, it is strongely recommended to handle filenames, I/O and other related topics UTF-8. Additionally, for the console applications, the usage of a TrueType font is preferable and the usage of ini_set() for the codepage change is discouraged.

readline

The readline extension is supported through the » WinEditLine library. Thereby, the interactive CLI shell is supported as well (php.exe -a).

PHP_FCGI_CHILDREN

PHP_FCGI_CHILDREN is now respected. If this environment variable is defined, the first php-cgi.exe process will exec the specified number of children. These will share the same TCP socket.

ftok()

Added support for ftok()

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 5.6.x to PHP 7.0.x

Table of Contents

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 7.0.x
  • Changed functions
  • New functions
  • New Classes and Interfaces
  • New Global Constants
  • Changes in SAPI Modules
  • Removed Extensions and SAPIs
  • Other Changes

Despite the fact that PHP 7.0 is a new major version, efforts have been made to make migration as painless as possible. This release focuses mainly on removing functionality deprecated in previous versions and improving language consistency.

There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Changes to error and exception handling

Many fatal and recoverable fatal errors have been converted to exceptions in PHP 7. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit).

This means that custom error handlers may no longer be triggered because exceptions may be thrown instead (causing new fatal errors for uncaught Error exceptions).

A fuller description of how errors operate in PHP 7 can be found on the PHP 7 errors page. This migration guide will merely enumerate the changes that affect backward compatibility.

set_exception_handler() is no longer guaranteed to receive Exception objects

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

Internal constructors always throw exceptions on failure

Previously, some internal classes would return null or an unusable object when the constructor failed. All internal classes will now throw an Exception in this case in the same way that user classes already had to.

Parse errors throw ParseError

Parser errors now throw a ParseError object. Error handling for eval() should now include a catch block that can handle this error.

E_STRICT notices severity changes

All of the E_STRICT notices have been reclassified to other levels. E_STRICT constant is retained, so calls like error_reporting(E_ALL|E_STRICT) will not cause an error.

E_STRICT notices severity changes
Situation | New level/behaviour
Indexing by a resource | E_NOTICE
Abstract static methods | Notice removed, triggers no error
"Redefining" a constructor | Notice removed, triggers no error
Signature mismatch during inheritance | E_WARNING
Same (compatible) property in two used traits | Notice removed, triggers no error
Accessing static property non-statically | E_NOTICE
Only variables should be assigned by reference | E_NOTICE
Only variables should be passed by reference | E_NOTICE
Calling non-static methods statically | E_DEPRECATED

Changes to variable handling

PHP 7 now uses an abstract syntax tree when parsing source files. This has permitted many improvements to the language which were previously impossible due to limitations in the parser used in earlier versions of PHP, but has resulted in the removal of a few special cases for consistency reasons, which has resulted in backward compatibility breaks. These cases are detailed in this section.

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

Old and new evaluation of indirect expressions
Expression | PHP 5 interpretation | PHP 7 interpretation
$$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 that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces (see the above middle column). This will make the code both forwards compatible with PHP 7.x and backwards compatible with PHP 5.x.

This also affects the global keyword. The curly brace syntax can be used to emulate the previous behaviour if required:

<?php
function f() {
// Valid in PHP 5 only.
global $$foo->bar;

// Valid in PHP 5 and 7.
global ${$foo->bar};
}
?>

Changes to list() handling

list() no longer assigns variables in reverse order

list() will now assign values to variables in the order they are defined, rather than reverse order. In general, this only affects the case where list() is being used in conjunction with the array [] operator, as shown below:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Output of the above example in PHP 5:

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

Output of the above example in PHP 7:

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

In general, it is recommended not to rely on the order in which list() assignments occur, as this is an implementation detail that may change again in the future.

Empty list() assignments have been removed

list() constructs can no longer be empty. The following are no longer allowed:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() cannot unpack strings

list() can no longer unpack string variables. str_split() should be used instead.

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Output of the above example in PHP 5:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Output of the above example in PHP 7:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Parentheses around function arguments no longer affect behaviour

In PHP 5, using redundant parentheses around a function argument could quiet strict standards warnings when the function argument was passed by reference. The warning will now always be issued.

<?php
function getArray() {
return [1, 2, 3];
}

function squareArray(array &$a) {
foreach ($a as &$v) {
$v **= 2;
}
}

// Generates a warning in PHP 7.
squareArray((getArray()));
?>

The above example will output:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Changes to foreach

Minor changes have been made to the behaviour of the foreach control structure, primarily around the handling of the internal array pointer and modification of the array being iterated over.

foreach no longer changes the internal array pointer

Prior to PHP 7, the internal array pointer was modified while an array was being iterated over with foreach. This is no longer the case, as shown in the following example:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}
?>

Output of the above example in PHP 5:

int(1)
int(2)
bool(false)

Output of the above example in PHP 7:

int(0)
int(0)
int(0)

foreach by-value operates on a copy of the array

When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated.

foreach by-reference has improved iteration behaviour

When iterating by-reference, foreach will now do a better job of tracking changes to the array made during iteration. For example, appending to an array while iterating will now result in the appended values being iterated over as well:

<?php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
?>

Output of the above example in PHP 5:

int(0)

Output of the above example in PHP 7:

int(0)
int(1)

Iteration of non-Traversable objects

Iterating over a non-Traversable object will now have the same behaviour as iterating over by-reference arrays. This results in the improved behaviour when modifying an array during iteration also being applied when properties are added to or removed from the object.

Changes to int handling

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

Negative bitshifts

Bitwise shifts by negative numbers will now throw an ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Output of the above example in PHP 5:

int(0)

Output of the above example in PHP 7:

Fatal error: Uncaught ArithmeticError: Bit shift by negative number in /tmp/test.php:2
Stack trace:
#0 {main}
  thrown in /tmp/test.php on line 2

Out of range bitshifts

Bitwise shifts (in either direction) beyond the bit width of an int will always result in 0. Previously, the behaviour of such shifts was architecture dependent.

Changes to Division By Zero

Previously, when 0 was used as the divisor for either the divide (/) or modulus (%) operators, an E_WARNING would be emitted and false would be returned. Now, the divide operator returns a float as either +INF, -INF, or NAN, as specified by IEEE 754. The modulus operator E_WARNING has been removed and will throw a DivisionByZeroError exception.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Output of the above example in PHP 5:

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Output of the above example in PHP 7:

Warning: Division by zero in %s on line %d
float(INF)

Warning: Division by zero in %s on line %d
float(NAN)

PHP Fatal error:  Uncaught DivisionByZeroError: Modulo by zero in %s line %d

Changes to string handling

Hexadecimal strings are no longer considered numeric

Strings containing hexadecimal numbers are no longer considered to be numeric. For example:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Output of the above example in PHP 5:

bool(true)
bool(true)
int(15)
string(2) "oo"

Output of the above example in PHP 7:

bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

filter_var() can be used to check if a string contains a hexadecimal number, and also to convert a string of that type to an int:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535)
?>

\u{ may cause errors

Due to the addition of the new Unicode codepoint escape syntax, strings containing a literal \u{ followed by an invalid sequence will cause a fatal error. To avoid this, the leading backslash should be escaped.

Removed functions

call_user_method() and call_user_method_array()

These functions were deprecated in PHP 4.1.0 in favour of call_user_func() and call_user_func_array(). You may also want to consider using variable functions and/or the ... operator.

All ereg* functions

All ereg functions were removed. PCRE is a recommended alternative.

mcrypt aliases

The deprecated mcrypt_generic_end() function has been removed in favour of mcrypt_generic_deinit().

Additionally, the deprecated mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() and mcrypt_ofb() functions have been removed in favour of using mcrypt_decrypt() with the appropriate MCRYPT_MODE_* constant.

All ext/mysql functions

All ext/mysql functions were removed. For details about choosing a different MySQL API, see Choosing a MySQL API.

All ext/mssql functions

All ext/mssql functions were removed.

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • Unified ODBC API

intl aliases

The deprecated datefmt_set_timezone_id() and
IntlDateFormatter::setTimeZoneID() aliases have been
removed in favour of datefmt_set_timezone() and
IntlDateFormatter::setTimeZone(), respectively.

set_magic_quotes_runtime()

set_magic_quotes_runtime(), along with its alias magic_quotes_runtime(), have been removed. They were deprecated in PHP 5.3.0, and became effectively non-functional with the removal of magic quotes in PHP 5.4.0.

set_socket_blocking()

The deprecated set_socket_blocking() alias has been removed in favour of stream_set_blocking().

dl() in PHP-FPM

dl() can no longer be used in PHP-FPM. It remains functional in the CLI and embed SAPIs.

GD Type1 functions

Support for PostScript Type1 fonts has been removed from the GD extension, resulting in the removal of the following functions:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

Using TrueType fonts and their associated functions is recommended instead.

Removed INI directives

Removed features

The following INI directives have been removed as their associated features have also been removed:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

The xsl.security_prefs directive has been removed. Instead, the XsltProcessor::setSecurityPrefs() method should be called to control the security preferences on a per-processor basis.

Other backward incompatible changes

New objects cannot be assigned by reference

The result of the new statement can no longer be assigned to a variable by reference:

<?php
class C {}
$c =& new C;
?>

Output of the above example in PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Output of the above example in PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Invalid class, interface and trait names

The following names cannot be used to name classes, interfaces or traits:

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

Furthermore, the following names should not be used. Although they will not generate an error in PHP 7.0, they are reserved for future use and should be considered deprecated.

  • resource
  • object
  • mixed
  • numeric

ASP and script PHP tags removed

Support for using ASP and script tags to delimit PHP code has been removed. The affected tags are:

Removed ASP and script tags
Opening tag | Closing tag
<% | %>
<%= | %>
<script language="php"> | </script>

Calls from incompatible context removed

Previously deprecated in PHP 5.6, static calls made to a non-static method with an incompatible context will now result in the called method having an undefined $this variable and a deprecation warning being issued.

<?php
class A {
public function test() { var_dump($this); }
}

// Note: Does NOT extend A
class B {
public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Output of the above example in PHP 5.6:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

Output of the above example in PHP 7:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8

Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

yield is now a right associative operator

The yield construct no longer requires parentheses, and has been changed to a right associative operator with precedence between print and =>. This can result in changed behaviour:

<?php
echo yield -1;
// Was previously interpreted as
echo (yield) - 1;
// And is now interpreted as
echo yield (-1);

yield $foo or die;
// Was previously interpreted as
yield ($foo or die);
// And is now interpreted as
(yield $foo) or die;
?>

Parentheses can be used to disambiguate those cases.

Functions cannot have multiple parameters with the same name

It is no longer possible to define two or more function parameters with the same name. For example, the following function will trigger an E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
//
}
?>

Functions inspecting arguments report the current parameter value

func_get_arg(), func_get_args(), debug_backtrace() and exception backtraces will no longer report the original value that was passed to a parameter, but will instead provide the current value (which might have been modified).

<?php
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);?>

Output of the above example in PHP 5:

1

Output of the above example in PHP 7:

2

Switch statements cannot have multiple default blocks

It is no longer possible to define two or more default blocks in a switch statement. For example, the following switch statement will trigger an E_COMPILE_ERROR:

<?php
switch (1) {
default:
break;
default:
break;
}
?>

$HTTP_RAW_POST_DATA removed

$HTTP_RAW_POST_DATA is no longer available. The php://input stream should be used instead.

# comments in INI files removed

Support for prefixing comments with # in INI files has been removed. ; (semi-colon) should be used instead. This change applies to php.ini, as well as files handled by parse_ini_file() and parse_ini_string().

JSON extension replaced with JSOND

The JSON extension has been replaced with JSOND, causing three minor BC breaks. Firstly, a number must not end in a decimal point (i.e. 34. must be changed to either 34.0 or 34). Secondly, when using scientific notation, the e exponent must not immediately follow a decimal point (i.e. 3.e3 must be changed to either 3.0e3 or 3e3). Finally, an empty string is no longer considered valid JSON.

Internal function failure on overflow

Previously, internal functions would silently truncate numbers produced from float-to-integer coercions when the float was too large to represent as an integer. Now, an E_WARNING will be emitted and null will be returned.

Fixes to custom session handler return values

Any predicate functions implemented by custom session handlers that return either false or -1 will be fatal errors. If any value from these functions other than a boolean, -1, or 0 is returned, then it will fail and an E_WARNING will be emitted.

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Note:

Don't rely on the order of elements which compare as equal; it might change anytime.

Misplaced break and continue statements

break and continue statements outside of a loop or switch control structure are now detected at compile-time instead of run-time as before, and trigger an E_COMPILE_ERROR.

Mhash is not an extension anymore

The Mhash extension has been fully integrated into the Hash extension. Therefore, it is no longer possible to detect Mhash support with extension_loaded(); use function_exists() instead. Furthermore, Mhash is no longer reported by get_loaded_extensions() and related features.

declare(ticks)

The declare(ticks) directive does no longer leak into different compilation units.

User Contributed Notes

There are no user contributed notes for this page.


New features

Scalar type declarations

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

The above example will output:

int(9)

To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function's return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.

Full documentation and examples of scalar type declarations can be found in the type declaration reference.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

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

The above example will output:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Full documentation and examples of return type declarations can be found in the return type declarations. reference.

Null coalescing operator

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Spaceship operator

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules.

<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Constant arrays using define()

Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.

<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);

echo ANIMALS[1]; // outputs "cat"
?>

Anonymous classes

Support for anonymous classes has been added via new class. These can be used in place of full class definitions for throwaway objects:

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

The above example will output:

object(class@anonymous)#2 (0) {
}

Full documentation can be found in the anonymous class reference.

Unicode codepoint escape syntax

This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

The above example will output:

ª
ª (same as before but with optional leading 0's)
香

Closure::call()

Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.

<?php
class A {private $x = 1;}

// Pre PHP 7 code
$getX = function() {return $this->x;};
$getXCB = $getX->bindTo(new A, 'A'); // intermediate closure
echo $getXCB();

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);

The above example will output:

1
1

Filtered unserialize()

This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

<?php

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

The above example will output:

10ffff
COMMERCIAL AT
bool(true)

In order to use this class, the Intl extension must be installed.

Expectations

Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.

While the old API continues to be maintained for compatibility, assert() is now a language construct, allowing the first parameter to be an expression rather than just a string to be evaluated or a bool value to be tested.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
?>

The above example will output:

Fatal error: Uncaught CustomError: Some error message

Full details on this feature, including how to configure it in both development and production environments, can be found on the manual page of the assert() language construct.

Group use declarations

Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.

<?php
// Pre PHP 7 code
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;

// PHP 7+ code
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};
?>

Generator Return Expressions

This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finished yielding values.

<?php

$gen = (function() {
yield 1;
yield 2;

return 3;
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

The above example will output:

1
2
3

Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator delegation

Generators can now delegate to another generator, Traversable object or array automatically, without needing to write boilerplate in the outermost generator by using the yield from construct.

<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}

function gen2()
{
yield 3;
yield 4;
}

foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
?>

The above example will output:

1
2
3
4

Integer division with intdiv()

The new intdiv() function performs an integer division of its operands and returns it.

<?php
var_dump(intdiv(10, 3));
?>

The above example will output:

int(3)

Session options

session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.

These options have also been expanded to support session.lazy_write, which is on by default and causes PHP to only overwrite any session file if the session data has changed, and read_and_close, which is an option that can only be passed to session_start() to indicate that the session data should be read and then the session should immediately be closed unchanged.

For example, to set session.cache_limiter to private and immediately close the session after reading it:

<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>

preg_replace_callback_array()

The new preg_replace_callback_array() function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

CSPRNG Functions

Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int().

list() can always unpack objects implementing ArrayAccess

Previously, list() was not guaranteed to operate correctly with objects implementing ArrayAccess. This has been fixed.

Other Features

  • Class member access on cloning has been added, e.g. (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


Deprecated features in PHP 7.0.x

PHP 4 style constructors

PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.

<?php
class foo {
function foo() {
echo 'I am the constructor';
}
}
?>

The above example will output:

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

Static calls to non-static methods

Static calls to methods that are not declared static are deprecated, and may be removed in the future.

<?php
class foo {
function bar() {
echo 'I am not static!';
}
}

foo::bar();
?>

The above example will output:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

password_hash() salt option

The salt option for the password_hash() function has been deprecated to prevent developers from generating their own (usually insecure) salts. The function itself generates a cryptographically secure salt when no salt is provided by the developer - therefore custom salt generation should not be needed.

capture_session_meta SSL context option

The capture_session_meta SSL context option has been deprecated. SSL metadata is now available through the stream_get_meta_data() function.

LDAP deprecations

The following function has been deprecated:

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


Changed functions

PHP Core

  • debug_zval_dump() now prints "int" instead of "long", and "float" instead of "double"
  • dirname() now optionally takes a second parameter, depth, to get the name of the directory depth levels up from the current directory.
  • getrusage() is now supported on Windows.
  • mktime() and gmmktime() functions no longer accept is_dst parameter.
  • preg_replace() function no longer supports "\e" (PREG_REPLACE_EVAL). preg_replace_callback() should be used instead.
  • setlocale() function no longer accepts category passed as string. LC_* constants must be used instead.
  • exec(), system() and passthru() functions have NULL byte protection now.
  • shmop_open() now returns a resource instead of an int, which has to be passed to shmop_size(), shmop_write(), shmop_read(), shmop_close() and shmop_delete().
  • substr() and iconv_substr() now return an empty string, if string is equal to start characters long.
  • xml_parser_free() is no longer sufficient to free the parser resource, if it references an object and this object references that parser resource. In this case it is necessary to additionally unset the $parser.

User Contributed Notes

There are no user contributed notes for this page.


New functions

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Error Handling and Logging

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

PHP Options/Info

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Zlib Compression

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Session Handling

  • SessionUpdateTimestampHandlerInterface

Exception Hierarchy

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

Core Predefined Constants

  • PHP_INT_MIN

GD

  • IMG_WEBP (as of PHP 7.0.10)

JSON

  • JSON_ERROR_INVALID_PROPERTY_NAME
  • JSON_ERROR_UTF16

LibXML

  • LIBXML_BIGLINES

PCRE

  • PREG_JIT_STACKLIMIT_ERROR

POSIX

  • POSIX_RLIMIT_AS
  • POSIX_RLIMIT_CORE
  • POSIX_RLIMIT_CPU
  • POSIX_RLIMIT_DATA
  • POSIX_RLIMIT_FSIZE
  • POSIX_RLIMIT_LOCKS
  • POSIX_RLIMIT_MEMLOCK
  • POSIX_RLIMIT_MSGQUEUE
  • POSIX_RLIMIT_NICE
  • POSIX_RLIMIT_NOFILE
  • POSIX_RLIMIT_NPROC
  • POSIX_RLIMIT_RSS
  • POSIX_RLIMIT_RTPRIO
  • POSIX_RLIMIT_RTTIME
  • POSIX_RLIMIT_SIGPENDING
  • POSIX_RLIMIT_STACK
  • POSIX_RLIMIT_INFINITY

Zlib

  • ZLIB_ENCODING_RAW
  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_FILTERED
  • ZLIB_HUFFMAN_ONLY
  • ZLIB_FIXED
  • ZLIB_RLE
  • ZLIB_DEFAULT_STRATEGY
  • ZLIB_BLOCK
  • ZLIB_FINISH
  • ZLIB_FULL_FLUSH
  • ZLIB_NO_FLUSH
  • ZLIB_PARTIAL_FLUSH
  • ZLIB_SYNC_FLUSH

User Contributed Notes

There are no user contributed notes for this page.


Changes in SAPI Modules

FPM

Unqualified listen ports now listen on both IPv4 and IPv6

In PHP 5, a listen directive with only a port number would listen on all interfaces, but only on IPv4. PHP 7 will now accept requests made via both IPv4 and IPv6.

This does not affect directives which include specific IP addresses; these will continue to only listen on that address and protocol.

User Contributed Notes

There are no user contributed notes for this page.


Removed Extensions and SAPIs

Removed Extensions

  • ereg
  • mssql
  • mysql
  • sybase_ct

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


Other Changes

Loosening Reserved Word Restrictions

Globally reserved words as property, constant, and method names within classes, interfaces, and traits are now allowed. This reduces the surface of BC breaks when new keywords are introduced and avoids naming restrictions on APIs.

This is particularly useful when creating internal DSLs with fluent interfaces:

<?php
// 'new', 'private', and 'for' were previously unusable
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

The only limitation is that the class keyword still cannot be used as a constant name, otherwise it would conflict with the class name resolution syntax (ClassName::class).

Removal of date.timezone Warning

Previously, a warning was emitted if the date.timezone INI setting had not been set prior to using any date- or time-based functions. Now, this warning has been removed (with date.timezone still defaulting to UTC).

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 5.5.x to PHP 5.6.x

Table of Contents

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 5.6.x
  • Changed functions
  • New functions
  • OpenSSL changes in PHP 5.6.x
  • Other changes to extensions
  • New global constants

Most improvements in PHP 5.6.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Array keys won't be overwritten when defining an array as a property of a class via an array literal

Previously, arrays declared as class properties which mixed explicit and implicit keys could have array elements silently overwritten if an explicit key was the same as a sequential implicit key. For example:

<?php
class C {
const ONE = 1;
public $array = [
self::ONE => 'foo',
'bar',
'quux',
];
}

var_dump((new C)->array);
?>

Output of the above example in PHP 5.5:

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

Output of the above example in PHP 5.6:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

json_decode() strictness

json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification, and sets json_last_error() accordingly. Previously, inputs to json_decode() that consisted solely of one of these values in upper or mixed case were accepted.

This change will only affect cases where invalid JSON was being passed to json_decode(): valid JSON input is unaffected and will continue to be parsed normally.

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to false, and to disable peer name validation by setting the verify_peer_name context option to false.

GMP resources are now objects

GMP resources are now objects. The functional API implemented in the GMP extension has not changed, and code should run unmodified unless it checks explicitly for a resource using is_resource() or similar.

Mcrypt functions now require valid keys and IVs

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() and mcrypt_ofb() will no longer accept keys or IVs with incorrect sizes, and block cipher modes that require IVs will now fail if an IV isn't provided.

cURL file uploads

Uploads using the @file syntax now require CURLOPT_SAFE_UPLOAD to be set to false. CURLFile should be used instead.

User Contributed Notes

There are no user contributed notes for this page.


New features

Constant expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;

public function f($a = ONE + self::THREE) {
return $a;
}
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

The above example will output:

4
The value of THREE is 3

It is also now possible to define a constant array using the const keyword:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

The above example will output:

a

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
// $params is an array containing the remaining arguments.
printf('$req: %d; $opt: %d; number of params: %d'."\n",
$req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

The above example will output:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3

Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

<?php
function add($a, $b, $c) {
return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

The above example will output:

6

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

<?php
printf("2 ** 3 == %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a == %d\n", $a);
?>

The above example will output:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.

<?php
namespace Name\Space {
const FOO = 42;
function f() { echo __FUNCTION__."\n"; }
}

namespace {
use const Name\Space\FOO;
use function Name\Space\f;

echo FOO."\n";
f();
}
?>

The above example will output:

42
Name\Space\f

phpdbg

PHP now includes an interactive debugger called phpdbg implemented as a SAPI module. For more information, please visit the phpdbg documentation.

Default character encoding

default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

The default value for this setting is UTF-8.

php://input is reusable

php://input may now be reopened and read as many times as required. This work has also resulted in a major reduction in the amount of memory required to deal with POST data.

Large file uploads

Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading

GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP:

<?php
$a = gmp_init(42);
$b = gmp_init(17);

if (version_compare(PHP_VERSION, '5.6', '<')) {
echo gmp_intval(gmp_add($a, $b)), PHP_EOL;
echo gmp_intval(gmp_add($a, 17)), PHP_EOL;
echo gmp_intval(gmp_add(42, $b)), PHP_EOL;
} else {
echo $a + $b, PHP_EOL;
echo $a + 17, PHP_EOL;
echo 42 + $b, PHP_EOL;
}
?>

The above example will output:

59
59
59

hash_equals() for timing attack safe string comparison

The hash_equals() function has been added to compare two strings in constant time. This should be used to mitigate timing attacks; for instance, when testing crypt() password hashes (assuming that you are unable to use password_hash() and password_verify(), which aren't susceptible to timing attacks).

<?php
$expected = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234', '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

The above example will output:

bool(true)
bool(false)

__debugInfo()

The __debugInfo() magic method has been added to allow objects to change the properties and values that are shown when the object is output using var_dump().

<?php
class C {
private $prop;

public function __construct($val) {
$this->prop = $val;
}

public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}

var_dump(new C(42));
?>

The above example will output:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

gost-crypto hash algorithm

The gost-crypto hash algorithm has been added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.

SSL/TLS improvements

A wide range of improvements have been made to the SSL/TLS support in PHP 5.6. These include enabling peer verification by default, supporting certificate fingerprint matching, mitigating against TLS renegotiation attacks, and many new SSL context options to allow more fine grained control over protocol and verification settings when using encrypted streams.

These changes are described in more detail in the OpenSSL changes in PHP 5.6.x section of this migration guide.

pgsql async support

The pgsql extension now supports asynchronous connections and queries, thereby enabling non-blocking behaviour when interacting with PostgreSQL databases. Asynchronous connections may be established via the PGSQL_CONNECT_ASYNC constant, and the new pg_connect_poll(), pg_socket(), pg_consume_input() and pg_flush() functions may be used to handle asynchronous connections and queries.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated features in PHP 5.6.x

Calls from incompatible context

Methods called from an incompatible context are now deprecated, and will generate E_DEPRECATED errors when invoked instead of E_STRICT. Support for these calls will be removed in a future version of PHP.

An example of such a call is:

<?php
class A {
function f() { echo get_class($this); }
}

class B {
function f() { A::f(); }
}

(new B)->f();
?>

The above example will output:

Deprecated: Non-static method A::f() should not be called statically, assuming $this from incompatible context in - on line 7
B

$HTTP_RAW_POST_DATA and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

iconv and mbstring encoding settings

The iconv and mbstring configuration options related to encoding have been deprecated in favour of default_charset. The deprecated options are:

  • iconv.input_encoding
  • iconv.output_encoding
  • iconv.internal_encoding
  • mbstring.http_input
  • mbstring.http_output
  • mbstring.internal_encoding

User Contributed Notes

There are no user contributed notes for this page.


Changed functions

PHP Core

  • crypt() will now raise an E_NOTICE error if the salt parameter is omitted.
  • substr_compare() will now accept 0 for its length parameter.
  • unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor.

cURL

  • Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to false. CURLFile should be used instead.

Mcrypt

  • The source parameter of mcrypt_create_iv() now defaults to MCRYPT_DEV_URANDOM instead of MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() now allows the crypto_type parameter to be optional if the stream's SSL context includes the new crypto_type option.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() and pg_delete() are no longer experimental.
  • pg_send_execute(), pg_send_prepare(), pg_send_query() and pg_send_query_params() will no longer block until query write completion if the underlying socket stream for the database connection is set to non-blocking mode.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() now allows non-final internal classes to be instantiated.

XMLReader

  • XMLReader::getAttributeNs() and XMLReader::getAttributeNo() now return null if the attribute could not be found, like XMLReader::getAttribute().

User Contributed Notes

There are no user contributed notes for this page.


New functions

Date and Time

  • DateTimeImmutable::createFromMutable()

GMP

  • gmp_root()
  • gmp_rootrem()

Hash

  • hash_equals()

LDAP

  • ldap_escape()
  • ldap_modify_batch()

MySQLi

  • mysqli_get_links_stats()

OCI8

  • oci_get_implicit_resultset()

OpenSSL

  • openssl_get_cert_locations()
  • openssl_x509_fingerprint()
  • openssl_spki_new()
  • openssl_spki_verify()
  • openssl_spki_export_challenge()
  • openssl_spki_export()

PostgreSQL

  • pg_connect_poll()
  • pg_consume_input()
  • pg_flush()
  • pg_socket()

PDO_PGSQL

  • PDO::pgsqlGetNotify()
  • PDO::pgsqlGetPid()

Session

  • session_abort()
  • session_reset()

Zip

  • ZipArchive::setPassword()

User Contributed Notes

There are no user contributed notes for this page.


OpenSSL changes in PHP 5.6.x

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to false, and to disable peer name validation by setting the verify_peer_name context option to false.

Certificate fingerprints

Support has been added for extracting and verifying certificate fingerprints. openssl_x509_fingerprint() has been added to extract a fingerprint from an X.509 certificate, and two SSL stream context options have been added: capture_peer_cert to capture the peer's X.509 certificate, and peer_fingerprint to assert that the peer's certificate should match the given fingerprint.

Default ciphers updated

The default ciphers used by PHP have been updated to a more secure list based on the » Mozilla cipher recommendations, with two additional exclusions: anonymous Diffie-Hellman ciphers, and RC4.

This list can be accessed via the new OPENSSL_DEFAULT_STREAM_CIPHERS constant, and can be overridden (as in previous PHP versions) by setting the ciphers context option.

Compression disabled by default

SSL/TLS compression has been disabled by default to mitigate the CRIME attack. PHP 5.4.13 added a disable_compression context option to allow compression to be disabled: this is now set to true (that is, compression is disabled) by default.

Allow servers to prefer their cipher order

The honor_cipher_order SSL context option has been added to allow encrypted stream servers to mitigate BEAST vulnerabilities by preferring the server's ciphers to the client's.

Access the negotiated protocol and cipher

The protocol and cipher that were negotiated for an encrypted stream can now be accessed via stream_get_meta_data() or stream_context_get_options() when the capture_session_meta SSL context option is set to true.

<?php
$ctx = stream_context_create(['ssl' => [
'capture_session_meta' => TRUE
]]);

$html = file_get_contents('https://google.com/', FALSE, $ctx);
$meta = stream_context_get_options($ctx)['ssl']['session_meta'];
var_dump($meta);
?>

The above example will output:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

New options for perfect forward secrecy in encrypted stream servers

Encrypted client streams already support perfect forward secrecy, as it is generally controlled by the server. PHP encrypted server streams using certificates capable of perfect forward secrecy do not need to take any additional action to enable PFS; however a number of new SSL context options have been added to allow more control over PFS and deal with any compatibility issues that may arise.

ecdh_curve

This option allows the selection of a specific curve for use with ECDH ciphers. If not specified, prime256v1 will be used.

dh_param

A path to a file containing parametrs for Diffie-Hellman key exchange, such as that created by the following command:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

If set to true, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.

single_ecdh_use

If set to true, a new key pair will always be generated when ECDH cipher suites are negotiated. This improves forward secrecy.

SSL/TLS version selection

It is now possible to select specific versions of SSL and TLS via the crypto_method SSL context option or by specifying a specific transport when creating a stream wrapper (for example, by calling stream_socket_client() or stream_socket_server()).

The crypto_method SSL context option accepts a bitmask enumerating the protocols that are permitted, as does the crypto_type of stream_socket_enable_crypto().

Selected protocol versions and corresponding options
Protocol(s) | Client flag | Server flag | Transport
Any TLS or SSL version | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Any TLS version | STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLS_SERVER | tls://
TLS 1.0 | STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | tlsv1.0://
TLS 1.1 | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | tlsv1.1://
TLS 1.2 | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER | tlsv1.2://
SSL 3 | STREAM_CRYPTO_METHOD_SSLv3_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_SERVER | sslv3://
<?php

// Requiring TLS 1.0 or better when using file_get_contents():
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requiring TLS 1.1 or 1.2:
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Connecting using the tlsv1.2:// stream socket transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() added

The openssl_get_cert_locations() function has been added: it returns the default locations PHP will search when looking for CA bundles.

<?php
var_dump(openssl_get_cert_locations());
?>

The above example will output:

array(8) {
  ["default_cert_file"]=>
  string(21) "/etc/pki/tls/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/etc/pki/tls/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/etc/pki/tls/private"
  ["default_default_cert_area"]=>
  string(12) "/etc/pki/tls"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

SPKI support

Support has been added for generating, extracting and verifying signed public key and challenges (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), and openssl_spki_export() have been added to create, verify export PEM public key and associated challenge from SPKAC's generated from a KeyGen HTML5 element.

openssl_spki_new

Generates a new SPKAC using private key, challenge string and hashing algorithm.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

The above example will output:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifies provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
var_dump(openssl_spki_verify($spkac));
?>
openssl_spki_export_challenge

Exports associated challenge from provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge($spkac);
echo $challenge;
?>

The above example will output:

challenge string
openssl_spki_export

Exports the PEM formatted RSA public key from SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

The above example will output:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----

User Contributed Notes

There are no user contributed notes for this page.


Other changes to extensions

cURL

A number of constants marked obsolete in the cURL library have now been removed:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Support for implicit result sets for Oracle Database 12c has been added via the new oci_get_implicit_resultset() function.
  • Using oci_execute($s, OCI_NO_AUTO_COMMIT) for a SELECT no longer unnecessarily initiates an internal ROLLBACK during connection close.
  • Added DTrace probes controlled by the --enable-dtrace configure option.
  • oci_internal_debug() is now a no-op.
  • The phpinfo() output format for OCI8 has changed.

Zip

A --with-libzip configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

MySQLi

A new mysqli.rollback_on_cached_plink option was added, which controls the rollback behavior of persistent connections.

User Contributed Notes

There are no user contributed notes for this page.


New global constants

GD

  • IMG_WEBP (as of PHP 5.6.25)

LDAP

  • LDAP_ESCAPE_DN
  • LDAP_ESCAPE_FILTER

OpenSSL

  • OPENSSL_DEFAULT_STREAM_CIPHERS
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

PostgreSQL

  • PGSQL_CONNECT_ASYNC
  • PGSQL_CONNECTION_AUTH_OK
  • PGSQL_CONNECTION_AWAITING_RESPONSE
  • PGSQL_CONNECTION_MADE
  • PGSQL_CONNECTION_SETENV
  • PGSQL_CONNECTION_SSL_STARTUP
  • PGSQL_CONNECTION_STARTED
  • PGSQL_DML_ESCAPE
  • PGSQL_POLLING_ACTIVE
  • PGSQL_POLLING_FAILED
  • PGSQL_POLLING_OK
  • PGSQL_POLLING_READING
  • PGSQL_POLLING_WRITING

User Contributed Notes

There are no user contributed notes for this page.


Debugging in PHP

Table of Contents

  • About 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!


About debugging in PHP

PHP is shipped with a basic command line interactive debugger, phpdbg.

Most IDEs have support for » Xdebug, a free debug tool, which allows for single step debugging your PHP applications.

User Contributed Notes

There are no user contributed notes for this page.


Configure options

Table of Contents

  • List of core configure options

User Contributed Notes

There are no user contributed notes for this page.


List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the » GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

Note:

These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Runtime Configuration.

  • Miscellaneous
  • PHP Behaviour
  • Server

Configure Options in PHP

Misc options

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU. Note that if installing manpages under PREFIX (default), choose the GNU style in order for them to be found in the search path of manpath utility.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

Include experimental PHP streams. Do not use unless you are testing the code!

--with-zlib-dir[=DIR]

Define the location of zlib install directory.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--enable-versioning

Export only required symbols. See INSTALL for more information.

PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--disable-short-tags

Disable the short-form <? start tag by default.

--with-libdir

Specifies the directory where the libraries to build PHP exist on a Unix system. For 64bit systems, its needed to specify this argument to the lib64 directory like: --with-libdir=lib64.

--enable-zts

Enables thread safety. Prior to PHP 8.0.0 on non-Windows systems, the option was called --enable-maintainer-zts.

SAPI options

The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build a static Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Russian Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--disable-cli

Disable building the CLI version of PHP (this forces --without-pear). More information is available in the section about Using PHP from the command line.

--enable-phpdbg

Enable phpdbg interactive debugger SAPI module support.

--enable-embed[=TYPE]

Enable building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI requires the java extension must be built as a shared dl.

--disable-cgi

Disable building CGI version of PHP.

This argument also enables FastCGI.

User Contributed Notes

atesin () gmail ! com 04-Feb-2021 08:55
i'll answer myself (FINALLY!)

current "configure options" can be viewed with "php-config" shell script, aside with other compile time options too =D!!! ...

in some distributions it comes with the "php-devel" package... but until in this online manual "php-config" is mentioned in pecl extensions documentation (i couldn't find on pecl site), idk if that "php-devel" has something to do with this

... however i noticed they are literal strings inside the script, i hope the script itself were built together with php compilation o_O

in the previous page "configure options" (link shown above ^), there is an editor note with additional info about it
atesin () gmail ! com 04-Feb-2021 02:38
please somebody tell me how to display configure options used in php actual binary

it was shown in phpinfo() some years before, it was very useful, specially with 'phpize' recompilation and to enable some pecl/pear module :/

please tell me also which ctriteria had php guys used to suddenly decided to hide (or obfuscate) this info :/

thanks in advance


php.ini directives

Table of Contents

  • List of php.ini directives
  • List of php.ini sections
  • Description of core php.ini directives

User Contributed Notes

There are no user contributed notes for this page.


List of php.ini directives

This list includes the php.ini directives you can set to configure your PHP setup.

The "Changeable" column shows the modes determining when and where a directive may be set. See the Changeable mode values section for their definitions.

Configuration options
Name | Default | Changeable | Changelog
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Deprecated as of PHP 7.4.0.
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL | Removed as of PHP 8.0.0
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
bcmath.scale | "0" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_ALL |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
cli.pager | "" | PHP_INI_ALL |
cli.prompt | "\\b \\> " | PHP_INI_ALL |
cli_server.color | "0" | PHP_INI_ALL |
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM |
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.833333" | PHP_INI_ALL | Prior to PHP 8.0.0, the default was "90.583333"
date.sunset_zenith | "90.833333" | PHP_INI_ALL | Prior to PHP 8.0.0, the default was "90.583333"
date.timezone | "UTC" | PHP_INI_ALL | From PHP 8.2, a warning is emitted when setting this to an invalid value or an empty string.
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Default to "UTF-8".
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | php.ini only |
disable_functions | "" | php.ini only |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "1" | PHP_INI_ALL | Prior to PHP 8.0.0, the default value was "0".
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | This deprecated feature will certainly be removed in the future.
enable_post_data_reading | On | PHP_INI_PERDIR |
engine | "1" | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_log_mode | 0o644 | PHP_INI_ALL | Available as of PHP 8.2.0
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL |
exif.encode_jis | "" | PHP_INI_ALL |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
exit_on_timeout | "" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
extension | NULL | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR | Deprecated as of PHP 8.1.0.
filter.default_flags | NULL | PHP_INI_PERDIR |
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
geoip.custom_directory | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | Available since PHP 7.1.0.
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.
iconv.input_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL |
include_path | ".:/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PECL 3.0.0a1
last_modified | "0" | PHP_INI_ALL |
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
mail.add_x_header | "0" | PHP_INI_PERDIR |
mail.force_extra_parameters | NULL | php.ini only |
mail.log | "" | PHP_INI_PERDIR |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
max_input_time | "-1" | PHP_INI_PERDIR |
mbstring.language | "neutral" | PHP_INI_ALL |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL | Deprecated
mbstring.http_output | "pass" | PHP_INI_ALL | Deprecated
mbstring.internal_encoding | NULL | PHP_INI_ALL | Deprecated
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL |
mbstring.strict_detection | "0" | PHP_INI_ALL |
mbstring.regex_retry_limit | "1000000" | PHP_INI_ALL | Available as of PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | PHP_INI_ALL | Available as of PHP 7.3.5.
mcrypt.algorithms_dir | null | PHP_INI_ALL |
mcrypt.modes_dir | null | PHP_INI_ALL |
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
memory_limit | "128M" | PHP_INI_ALL |
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL |
mysqli.allow_local_infile | "0" | PHP_INI_SYSTEM | Before PHP 7.2.16 and 7.3.3 the default was "1".
mysqli.local_infile_directory |  | PHP_INI_SYSTEM | Available as of PHP 8.1.0.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM |
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM |
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Removed as of PHP 8.2.0
mysqli.rollback_on_cached_plink | "0" | PHP_INI_SYSTEM |
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM |
mysqlnd.debug | "" | PHP_INI_SYSTEM |
mysqlnd.log_mask | 0 | PHP_INI_ALL |
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
mysqlnd.net_read_timeout | "86400" | PHP_INI_ALL | Before PHP 7.2.0 the default value was "31536000" and the changeability was PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR |
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Removed as of PHP 8.1.0
oci8.connection_class | "" | PHP_INI_ALL |
oci8.default_prefetch | "100" | PHP_INI_SYSTEM |
oci8.events | Off | PHP_INI_SYSTEM |
oci8.max_persistent | "-1" | PHP_INI_SYSTEM |
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Deprecated as of PHP 8.1.0.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM |
oci8.ping_interval | "60" | PHP_INI_SYSTEM |
oci8.prefetch_lob_size | "0" | PHP_INI_SYSTEM | Available since PECL OCI8 3.2.
oci8.privileged_connect | Off | PHP_INI_SYSTEM |
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM |
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL |
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Between PHP 7.1.2 and 7.1.6 inclusive, the default was "1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM |
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM |
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM |
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | Removed in PHP 7.2.0
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | Changed from 0x7FFFBFFF in PHP 7.3.0
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Removed in PHP 7.3.0
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL | Disabled as of 8.1.18 and 8.2.5. Removed as of PHP 8.3.0.
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.record_warnings | "0" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | null | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM | Available as of PHP 7.1.0
opcache.file_cache | NULL | PHP_INI_SYSTEM |
opcache.file_cache_only | "0" | PHP_INI_SYSTEM |
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM |
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Windows only.
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.cache_id | "" | PHP_INI_SYSTEM | Windows only. Available as of PHP 7.4.0
opcache.jit | "tracing" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_buffer_size | "0" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_debug | "0" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_bisect_limit | "0" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_prof_threshold | "0.005" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_root_traces | "1024" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_max_side_traces | "128" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_max_exit_counters | "8192" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_loop | "64" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_func | "127" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_return | "8" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_hot_side_exit | "8" | PHP_INI_SYSTEM | Available as of PHP 8.0.0
opcache.jit_blacklist_root_trace | "16" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_blacklist_side_trace | "8" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_loop_unrolls | "8" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_recursive_calls | "2" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_recursive_returns | "2" | PHP_INI_ALL | Available as of PHP 8.0.0
opcache.jit_max_polymorphic_calls | "2" | PHP_INI_ALL | Available as of PHP 8.0.0
open_basedir | NULL | PHP_INI_ALL |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL |
pcre.recursion_limit | "100000" | PHP_INI_ALL |
pcre.jit | "1" | PHP_INI_ALL |
pdo.dsn.* |  | php.ini only |
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | This deprecated feature will certainly be removed in the future.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM |
pgsql.ignore_notice | "0" | PHP_INI_ALL |
pgsql.log_notice | "0" | PHP_INI_ALL |
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.cache_list | "" | PHP_INI_SYSTEM |
post_max_size | "8M" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM |
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |
register_argc_argv | "1" | PHP_INI_PERDIR |
report_memleaks | "1" | PHP_INI_ALL |
report_zend_debug | "1" | PHP_INI_ALL |
request_order | "" | PHP_INI_PERDIR |
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "-1" | PHP_INI_ALL | Prior to PHP 7.1.0, the default value was 17.
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_PERDIR |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL |
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "0" | PHP_INI_ALL | Prior to PHP 7.2.0, the default was "".
session.cookie_httponly | "0" | PHP_INI_ALL | Prior to PHP 7.2.0, the default was "".
session.cookie_samesite | "" | PHP_INI_ALL | Available as of PHP 7.3.0.
session.use_strict_mode | "0" | PHP_INI_ALL |
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Available as of PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Available as of PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Available as of PHP 7.1.0.
session.sid_bits_per_character | "4" | PHP_INI_ALL | Available as of PHP 7.1.0.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR |
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR |
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR |
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR |
session.upload_progress.freq | "1%" | PHP_INI_PERDIR |
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR |
session.lazy_write | "1" | PHP_INI_ALL |
session.hash_function | "0" | PHP_INI_ALL | Removed as of PHP 7.1.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Removed as of PHP 7.1.0.
session.entropy_file | "" | PHP_INI_ALL | Removed as of PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Removed as of PHP 7.1.0
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite3.extension_dir | "" | PHP_INI_SYSTEM |
sqlite3.defensive | 1 | PHP_INI_USER | Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0. Prior to PHP 8.2.0 this setting was changeable only as PHP_INI_SYSTEM.
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Available as of PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
sys_temp_dir | "" | PHP_INI_SYSTEM |
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER |
track_errors | "0" | PHP_INI_ALL | Deprecated as of PHP 7.2.0, removed as of PHP 8.0.0
unserialize_callback_func | null | PHP_INI_ALL |
unserialize_max_depth | "4096" | PHP_INI_ALL | Available as of PHP 7.4.0.
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
uopz.disable | "0" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
variables_order | "EGPCS" | PHP_INI_PERDIR |
windows.show_crt_warning | "0" | PHP_INI_ALL |
xbithack | "0" | PHP_INI_ALL |
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_mask | NULL | PHP_INI_ALL | Available since yaz 1.0.3.
zend.assertions | "1" | PHP_INI_ALL |
zend.detect_unicode | "1" | PHP_INI_ALL |
zend.enable_gc | "1" | PHP_INI_ALL |
zend.multibyte | "0" | PHP_INI_PERDIR |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend_extension | NULL | php.ini only |
zlib.output_compression | "0" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |

User Contributed Notes

There are no user contributed notes for this page.


List of php.ini sections

This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional.

These sections don't directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path.

These sections are used only in CGI/FastCGI mode and they can not set extension and zend_extension directives.

Sections
Name | Changeable | Changelog
[HOST=] | PHP_INI_SYSTEM |
[PATH=] | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

[HOST=<host>]

This section allows you to define a set of php.ini directives that will take effect on the named host.

Example #1 Activate full on-screen error reporting for dev. domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

This section allows you to define a set of php.ini directives that will take effect when a script runs from the named path.

Example #2 Add security script for protected areas

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

User Contributed Notes

dasloch at absatzen dot de 12-Feb-2020 12:47
Note that you cannot usefully set syslog.* in [PATH=] (and probably [HOST=]) sections, since the syslogger is initialized only once per php-fpm worker process, and not per request.
robinhook at mail dot com 22-Apr-2018 07:14
Sorry for the note. I've read some bad tutorials.
The correct syntax is : directive = 'value'
not a thing like : php_value[directive] = "somevalue"
robinhook at mail dot com 22-Apr-2018 06:59
this HOST and PATH sections doesn't seems to work in php.ini under apache 2.4 with php-fpm 7.1.16 for directive php_value or php_admin_value open_basedir or include_path.
phpinfo() says "none" in master and local values.
z dot himdi at bita dot nl 04-Aug-2011 07:53
On Windows IIS 7 server I noticed that [PATH=] was not listened to. [HOST=] however worked.
leo 06-May-2011 03:21
Just developed the probably first php.ini hack to add commands which will only be parsed before PHP 5.3 when using mod_php.

<?php

# Disable eAccelerator by default
eaccelerator.enable = 0

# Now, to prevent incompatibilities with Zend Optimizer+, we
# want to enable eAccelerator only in PHP 5.2 or lower.
[HOST=*]
eaccelerator.enable = 1

?>

What is happening here? In PHP 5.3, php.ini sections to set up PHP on a per host basis have been introduced:

http://www.php.net/manual/en/ini.sections.php

These sections only work in CGI/FastCGI mode, however there still seems to be a difference in how the php.ini file is parsed in PHP 5.2 and PHP 5.3 when using mod_php: PHP 5.3 ignores everything below the line [HOST=*], whereas PHP 5.2 does not.

In the above example, PHP 5.3 only reads "eaccelerator.enable = 0" and then stops at the invalid command [HOST=*]. However, PHP 5.2 seems to ignore the invalid command and parses the whole configuration file, ending up with "eaccelerator.enable = 1".
crash at lubyte dot de 06-Sep-2010 05:45
If you have a system which uses separated PHP inis for loading extensions (Debian, Fedora and most other distributions do so), [PATH=] or [HOST=] will prevent loading extensions defined in those ini files (extension= and zend_extension=).

I had some headache, when I added a hosts.ini to /etc/php5/cgi/conf.d (Debians default), where I wanted to define some defaults for a host name. The manual says extension= and zend_extension= aren't allowed in [HOST=] and [PATH=] (see above). I figured out that you can easily fix that with adding [PHP] after your definitions.

For example hosts.ini:
[HOST=dev.example.com]
display_errors = on

[PHP]

this will change the section back to [PHP] where extension= and zend_extension= is allowed.
robert dot johnson at icap dot com 12-Apr-2010 10:26
Adding PATH= applies only to the named path and does not include sub-directories, you have to add a PATH= value for each sub-directory.

Also some settings have no effect even though phpinfo recognises and displays the per-folder value as the 'local' value, and the default as the 'master' value.

'fastcgi.impersonate' always uses the master setting.
public at grik dot net 24-Sep-2009 03:00
In [HOST=...] one should use only the 1st server name from the list of server names.

I.E. if you have
server_name example.com, example2.com;
and will use www.example.com in a browser,
use [HOST=example.com] in php.ini for both addresses.

PHP looks not at the HOST request header (as I expected), but at the SERVER_NAME parameter (which by default is the 1st from the list of names, no matter what the HOST is).


Description of core php.ini directives

This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page.

Note:

The defaults listed here are used when php.ini is not loaded; the values for the production and development php.ini may vary.

Language Options

Language and Misc Configuration Options
Name | Default | Changeable | Changelog
short_open_tag | "1" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Prior to PHP 7.1.0, the default value was 17.
disable_functions | "" | PHP_INI_SYSTEM only |
disable_classes | "" | php.ini only |
exit_on_timeout | "" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
hard_timeout | "2" | PHP_INI_SYSTEM | Available as of PHP 7.1.0.
zend.exception_ignore_args | "0" | PHP_INI_ALL | Available as of PHP 7.4.0
zend.multibyte | "0" | PHP_INI_ALL |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.detect_unicode | NULL | PHP_INI_ALL |
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend.assertions | "1" | PHP_INI_ALL with restrictions |
zend.exception_string_param_max_len | "15" | PHP_INI_ALL | Available as of PHP 8.0.0.

Here's a short explanation of the configuration directives.

short_open_tag bool

Tells PHP whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>. Also, if disabled, you must use the long form of the PHP open tag (<?php ?>).

Note:

This directive does not affect the shorthand <?=, which is always available.

precision int
The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.
serialize_precision int
The number of significant digits stored while serializing floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.
expose_php bool

Exposes to the world that PHP is installed on the server, which includes the PHP version within the HTTP header (e.g., X-Powered-By: PHP/5.3.7).

disable_functions string

This directive allows you to disable certain functions. It takes on a comma-delimited list of function names.

Only internal functions can be disabled using this directive. User-defined functions are unaffected.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

disable_classes string
This directive allows you to disable certain classes. It takes on a comma-delimited list of class names. This directive must be set in php.ini For example, you cannot set this in httpd.conf.
zend.assertions int
When set to 1, assertion code will be generated and executed (development mode). When set to 0, assertion code will be generated but it will be skipped (not executed) at runtime. When set to -1, assertion code will not be generated, making the assertions zero-cost (production mode).

Note:

If a process is started in production mode, zend.assertions cannot be changed at runtime, since the code for assertions was not generated.

If a process is started in development mode, zend.assertions cannot be set to -1 at runtime.

zend.exception_string_param_max_len int
The maximum length of string function arguments in stringified stack traces. Must range between "0" and "1000000".
hard_timeout int

When the timeout set in max_execution_time has been hit, the PHP runtime will tear down resources gracefully. If something gets stuck while this happens, the hard timeout will tick for the set amount of seconds. When the hard timeout is hit, PHP will exit ungracefully. When set to 0, the hard timeout will never activate.

When PHP stops from a hard timeout, it will look something like this:

Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0

zend.exception_ignore_args bool

Excludes arguments from stack traces generated from exceptions.

zend.multibyte bool

Enables parsing of source files in multibyte encodings. Enabling zend.multibyte is required to use character encodings like SJIS, BIG5, etc that contain special characters in multibyte string data. ISO-8859-1 compatible encodings like UTF-8, EUC, etc do not require this option.

Enabling zend.multibyte requires the mbstring extension to be available.

zend.script_encoding string

This value will be used unless a declare(encoding=...) directive appears at the top of the script. When ISO-8859-1 incompatible encoding is used, both zend.multibyte and zend.script_encoding must be used.

Literal strings will be transliterated from zend.script_encoding to mbstring.internal_encoding, as if mb_convert_encoding() would have been called.

zend.detect_unicode bool

Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode.

zend.signal_check bool

To check for replaced signal handlers on shutdown.

exit_on_timeout bool

This is an Apache1 mod_php-only directive that forces an Apache child to exit if a PHP execution timeout occurred. Such a timeout causes an internal longjmp() call in Apache1 which can leave some extensions in an inconsistent state. By terminating the process any outstanding locks or memory will be cleaned up.

Resource Limits

Resource Limits
Name | Default | Changeable | Changelog
memory_limit | "128M" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

memory_limit int

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.

See also: max_execution_time.

Performance Tuning

Performance Tuning
Name | Default | Changeable | Changelog
realpath_cache_size | "4M" | PHP_INI_SYSTEM | Prior to PHP 7.0.16 and 7.1.2, the default was "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |

Note:

Using open_basedir will disable the realpath cache.

Here's a short explanation of the configuration directives.

realpath_cache_size int

Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed.

The size represents the total number of bytes in the path strings stored, plus the size of the data associated with the cache entry. This means that in order to store longer paths in the cache, the cache size must be larger. This value does not directly control the number of distinct paths that can be cached.

The size required for the cache entry data is system dependent.

realpath_cache_ttl int

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Data Handling

Data Handling Configuration Options
Name | Default | Changeable | Changelog
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR |
request_order | "" | PHP_INI_PERDIR |
auto_globals_jit | "1" | PHP_INI_PERDIR |
register_argc_argv | "1" | PHP_INI_PERDIR |
enable_post_data_reading | "1" | PHP_INI_PERDIR |
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL |
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Note:

Every character in this directive is considered as separator!

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set.

Warning

In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.

Note:

The content and order of $_REQUEST is also affected by this directive.

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.

auto_globals_jit bool

When enabled, the SERVER, REQUEST, and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

Warning

Usage of SERVER, REQUEST, and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.

register_argc_argv bool
Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line.
enable_post_data_reading bool
Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.
post_max_size int
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size. When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set.

Note:

PHP allows shortcuts for byte values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you're using 32bit versions) as it will cause your script to fail.

Changelog for post_max_size
Version | Description
5.3.4 | post_max_size = 0 will not disable the limit when the content type is application/x-www-form-urlencoded or is not registered with PHP.
5.3.2 , 5.2.12 | Allow unlimited post size by setting post_max_size to 0.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-appending.

Note: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

By default, PHP will output a media type using the Content-Type header. To disable this, simply set it to be empty.

PHP's built-in default media type is set to text/html.

default_charset string

"UTF-8" is the default value and its value is used as the default character encoding for htmlentities(), html_entity_decode() and htmlspecialchars() if the encoding parameter is omitted. The value of default_charset will also be used to set the default character set for iconv functions if the iconv.input_encoding, iconv.output_encoding and iconv.internal_encoding configuration options are unset, and for mbstring functions if the mbstring.http_input mbstring.http_output mbstring.internal_encoding configuration option is unset.

All versions of PHP will use this value as the charset within the default Content-Type header sent by PHP if the header isn't overridden by a call to header().

Setting default_charset to an empty value is not recommended.

input_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

output_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

internal_encoding string

This setting is used for multibyte modules such as mbstring and iconv. Default is empty. If empty, default_charset is used.

Paths and Directories

Paths and Directories Configuration Options
Name | Default | Changeable | Changelog
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini only |
zend_extension | NULL | php.ini only |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_SYSTEM |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

include_path string

Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with an E_WARNING or an E_ERROR. You may modify or set your include path at runtime using set_include_path().

Example #1 Unix include_path

include_path=".:/php/includes"

Example #2 Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

Note:

ENV variables are also accessible in .ini files. As such it is possible to reference the home directory using ${LOGIN} and ${USER}.

Environment variables may vary between Server APIs as those environments may be different.

Example #3 Unix include_path using ${USER} env variable

include_path = ".:${USER}/pear/php"

open_basedir string

Limit the files that can be accessed by PHP to the specified directory-tree, including the file itself.

When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. If the file doesn't exist then the symlink couldn't be resolved and the filename is compared to (a resolved) open_basedir.

open_basedir can affect more than just filesystem functions; for example if MySQL is configured to use mysqlnd drivers, LOAD DATA INFILE will be affected by open_basedir. Much of the extended functionality of PHP uses open_basedir in this way.

The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().

In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is a directory name, not a prefix.

The default is to allow all files to be opened.

Note:

open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set(). When listing several directories, you can use the PATH_SEPARATOR constant as a separator regardless of the operating system.

Note:

Using open_basedir will set realpath_cache_size to 0 and thus disable the realpath cache.

Caution

open_basedir is just an extra safety net, that is in no way comprehensive, and can therefore not be relied upon when security is needed.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. It is recommended to specify an absolute path. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

zend_extension string

Name of dynamically loadable Zend extension (for example XDebug) to load when PHP starts up.

cgi.check_shebang_line bool

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.discard_path bool

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

cgi.fix_pathinfo bool

Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect bool

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Note:

Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies.

cgi.nph bool

If cgi.nph is enabled it will force cgi to always sent Status: 200 with every request.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Note:

Setting this variable may cause security issues, know what you are doing first.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set to 0, PHP sends a » RFC 3875 "Status:" header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers.

If this option is enabled, and you are running PHP in a CGI environment (e.g. PHP-FPM) you should not use standard RFC 2616 style HTTP status response headers, you should instead use their RFC 3875 equivalent e.g. instead of header("HTTP/1.0 404 Not found"); you should use header("Status: 404 Not Found");

Leave it set to 0 unless you know what you're doing.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

fastcgi.logging bool

Turns on SAPI logging when using FastCGI. Default is to enable logging.

File Uploads

File Uploads Configuration Options
Name | Default | Changeable | Changelog
file_uploads | "1" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_PERDIR |

Here's a short explanation of the configuration directives.

file_uploads bool

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

upload_max_filesize int

The maximum size of an uploaded file.

post_max_size must be larger than this value.

When an int is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
max_file_uploads int

The maximum number of files allowed to be uploaded simultaneously. Upload fields left blank on submission do not count towards this limit.

General SQL

General SQL Configuration Options
Name | Default | Changeable | Changelog
sql.safe_mode | "0" | PHP_INI_SYSTEM | Removed as of PHP 7.2.0

Here's a short explanation of the configuration directives.

sql.safe_mode bool

If turned on, database connection functions that specify default values will use those values in place of any user-supplied arguments. For details on the default values, see the documentation for the relevant connection functions.

Warning

This feature has been REMOVED as of PHP 7.2.0.

Windows Specific

Windows Specific Configuration Options
Name | Default | Changeable | Changelog
windows.show_crt_warning | "0" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

windows.show_crt_warning bool

This directive shows the Windows CRT warnings when enabled.

User Contributed Notes

andre dot wetter at myelco dot ch 23-Mar-2021 09:55
If you use Microsoft IIS Windows and want to use open_basedir restrictions with multiple dirs you have to set them into single quotes in the main config xml file of IIS (C:\Windows\System32\inetsrv\config\applicationHost.config). Works fine in IIS 10.

Multiple files with single quotes and ; for windows:
"C:\php\php-cgi.exe|-d open_basedir='C:\Windows\Temp\;D:\mywebsite1\'"

Only one dir works fine without single quotes:
"C:\php\php-cgi.exe|-d open_basedir=D:\mywebsite1\"

In my main config xml file of IIS there are 2 nodes to set per website and the definitions have to be equal:
configuration\Location\system.webServer\handlers\add
configuration\system.webServer\fastCgi
Simone Pellegatta 19-Jan-2021 12:08
Be careful while using auto_prepend_file.

When the custom exception handler, set by set_exception_handler(), handles an uncaught exception, it interrupts the execution of every script.

If the script with the unhandled exception has been automatically prepended or included by an automatically prepended script, however, the main script will continue running anyway.

This could cause several issues: when we think that throwing an exception would automatically interrupt the current application, a whole chunk of code is going to run anyway.
Anton Bannikov 22-Apr-2020 02:40
I had a problem with 'open_basedir =' string in php.ini. This string was writtren in VirtualHost Directory directive of Apache2 and successfully rewrote the same php.ini setting! It happened with VestaCP, but I think, it's a common way. Goog luck!
luisdev 03-Mar-2020 02:59
https://haydenjames.io/understanding-php-memory_limit/ explains the memory_limit setting nicely.
diamondeagle at webmail dot co dot za 15-Aug-2019 11:14
Note regarding the upload_tmp_dir setting and UNC Paths:

When using PHP on Windows OS and IIS FastCGI, if you need to use a UNC path to a folder on a network drive for the upload_tmp_dir setting then you must use three \ characters at the front of the UNC path.

Windows and PHP use the first slash as an escape character, so if you only use two slashes then it passes a UNC path with just one backslash. That is not valid for UNC paths and you many experience problems when uploading files, such as errors saying that "PHP is missing a temporary folder".

Correct:
upload_tmp_dir = "\\\path\to\your\folder"

Incorrect:
upload_tmp_dir = "\\path\to\your\folder"
fernandobasso dot br at gmail dot com 17-Oct-2016 08:06
This might help in case someone happens to maintain old applications with a charset other than utf-8.

According to the docs, you can override the default charset if you use `header()`.

Suppose php.ini sets the default_charset to "UTF-8", but you need a legacy charset, like ISO-8859-1.

Still,

<?php header('Content-Type: text/html; Charset=ISO-8859-1'); ?>

would not override the charset, just add it as well and the result
was a response header like (note the two charsets):

    Content-Type:"text/html; Charset=ISO-8859-1;charset=UTF-8"

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 List/Categorization

Table of Contents

  • Alphabetical
  • Membership
  • State

This appendix categorizes more than 150 extensions documented in the PHP Manual by several criteria.

User Contributed Notes

There are no user contributed notes for this page.


Alphabetical

  • Apache
  • APCu
  • Arrays
  • BC Math
  • Bzip2
  • Calendar
  • Classes/Objects
  • CommonMark
  • COM
  • Componere
  • Ctype
  • CUBRID
  • cURL
  • Date/Time
  • DBA
  • dBase
  • Direct IO
  • Directories
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Error Handling
  • Ev
  • Event
  • Program execution
  • Exif
  • Expect
  • FANN
  • FDF
  • FFI
  • Fileinfo
  • Filesystem
  • Filter
  • FastCGI Process Manager
  • FTP
  • Function Handling
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • Igbinary
  • GD
  • ImageMagick
  • IMAP
  • PHP Options/Info
  • 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
  • Output Control
  • 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
  • Strings
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Variable handling
  • 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.


Membership

Core Extensions

These are not actual extensions. They are part of the PHP core and cannot be left out of a PHP binary with compilation options.

  • Arrays

  • Classes/Objects

  • Date/Time

  • Directories

  • Error Handling

  • Program execution

  • Filesystem

  • FastCGI Process Manager

  • Function Handling

  • Hash

  • PHP Options/Info

  • JSON

  • Mail

  • Math

  • Misc.

  • Network

  • OPcache

  • Output Control

  • Password Hashing

  • PCRE

  • Random

  • Reflection

  • SPL

  • Streams

  • Strings

  • URLs

  • Variable handling

Bundled Extensions

These extensions are bundled with PHP.

  • Apache

  • BC Math

  • Calendar

  • COM

  • Ctype

  • DBA

  • Exif

  • FFI

  • Fileinfo

  • Filter

  • FTP

  • HRTime

  • iconv

  • GD

  • intl

  • Multibyte String

  • Mhash

  • PCNTL

  • PDO

  • Phar

  • phpdbg

  • POSIX

  • Semaphore

  • Sessions

  • Shared Memory

  • Sockets

  • SQLite3

  • Tokenizer

  • Zlib

External Extensions

These extensions are bundled with PHP but in order to compile them, external libraries will be needed.

  • 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

These extensions are available from » PECL. They may require external libraries. More PECL extensions exist but they are not documented in the PHP manual yet.

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


State

This part lists extensions not intended for the production use - they are either too "old" (deprecated) or "new" (experimental).

Deprecated Extensions

These extensions have been deprecated usually in the favor of some other extensions.

Experimental Extensions

The behaviour of these extensions - including the names of their functions and anything else documented about these extensions - may change without notice in a future release of PHP. Use these extensions at your own risk.

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


List of Function Aliases

There are quite a few functions in PHP which you can call with more than one name. In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. However there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.

Aliases
Alias | Master function | Extension used
_ | 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.


List of Reserved Words

Table of Contents

  • List of Keywords
  • Predefined Classes
  • Predefined Constants
  • List of other reserved words

The following is a listing of predefined identifiers in PHP. None of the identifiers listed here should be used as identifiers in any of your scripts unless explicitly noted otherwise. These lists include keywords and predefined variables, constant, and class names. These lists are neither exhaustive nor complete.

User Contributed Notes

There are no user contributed notes for this page.


List of Keywords

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on - but they're not, really: they are language constructs. The following words cannot be used as constants, class names, or function names. They are, however, allowed as property, constant, and method names of classes, interfaces and traits, except that class may not be used as constant name.

PHP Keywords
__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 (as of PHP 7.4) | for | foreach
function | global | goto | if | implements
include | include_once | instanceof | insteadof | interface
isset() | list() | match (as of PHP 8.0) | namespace | new
or | print | private | protected | public
readonly (as of PHP 8.1.0) * | require | require_once | return | static
switch | throw | trait | try | unset()
use | var | while | xor | yield
yield from |  |  |  |

* readonly may be used as function name.

Compile-time constants
__CLASS__ | __DIR__ | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ | __TRAIT__ |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords = array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.


Predefined Classes

This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference.

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory
Created by dir().
stdClass
A generic empty class created as a result of typecasting to object or various standard functions.
__PHP_Incomplete_Class
Possibly created by unserialize().
Exception
ErrorException
php_user_filter
Closure
The predefined final class Closure is used for representing anonymous functions.
Generator
The predefined final class Generator is used for representing generators.
ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Special classes

Following identifiers may not be used as a class name as they have special purpose.

self
Current class.
static
Current class in runtime.
parent
Parent class.

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


Predefined Constants

Core Predefined Constants

These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.

PHP_VERSION (string)
The current PHP version as a string in "major.minor.release[extra]" notation.
PHP_MAJOR_VERSION (int)
The current PHP "major" version as an integer (e.g., int(5) from version "5.2.7-extra").
PHP_MINOR_VERSION (int)
The current PHP "minor" version as an integer (e.g., int(2) from version "5.2.7-extra").
PHP_RELEASE_VERSION (int)
The current PHP "release" version as an integer (e.g., int(7) from version "5.2.7-extra").
PHP_VERSION_ID (int)
The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version "5.2.7-extra").
PHP_EXTRA_VERSION (string)
The current PHP "extra" version as a string (e.g., '-extra' from version "5.2.7-extra"). Often used by distribution vendors to indicate a package version.
PHP_ZTS (int)
PHP_DEBUG (int)
PHP_MAXPATHLEN (int)
The maximum length of filenames (including path) supported by this build of PHP.
PHP_OS (string)
The operating system PHP was built for.
PHP_OS_FAMILY (string)
The operating system family PHP was built for. One of 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' or 'Unknown'. Available as of PHP 7.2.0.
PHP_SAPI (string)
The Server API for this build of PHP. See also php_sapi_name().
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform.
PHP_INT_MAX (int)
The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems.
PHP_INT_MIN (int)
The smallest integer supported in this build of PHP. Usually int(-2147483648) in 32 bit systems and int(-9223372036854775808) in 64 bit systems. Usually, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)
The size of an integer in bytes in this build of PHP.
PHP_FLOAT_DIG (int)
Number of decimal digits that can be rounded into a float and back without precision loss. Available as of PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
Smallest representable positive number x, so that x + 1.0 != 1.0. Available as of PHP 7.2.0.
PHP_FLOAT_MIN (float)
Smallest representable positive floating point number. If you need the smallest representable negative floating point number, use - PHP_FLOAT_MAX. Available as of PHP 7.2.0.
PHP_FLOAT_MAX (float)
Largest representable floating point number. Available as of PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
The default directory where to look for dynamically loadable extensions (unless overridden by extension_dir). Defaults to PHP_PREFIX (or PHP_PREFIX . "\\ext" on Windows).
PHP_PREFIX (string)
The value --prefix was set to at configure. On Windows, it is the value --with-prefix was set to at configure.
PHP_BINDIR (string)
The value --bindir was set to at configure. On Windows, it is the value --with-prefix was set to at configure.
PHP_BINARY (string)
Specifies the PHP binary path during script execution.
PHP_MANDIR (string)
Specifies where the manpages were installed into.
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)
The build-platform's shared library suffix, such as "so" (most Unixes) or "dll" (Windows).
PHP_FD_SETSIZE (int)
The maximum number of file descriptors for select system calls. Available as of PHP 7.1.0.
E_ERROR (int)
Error reporting constant
E_WARNING (int)
Error reporting constant
E_PARSE (int)
Error reporting constant
E_NOTICE (int)
Error reporting constant
E_CORE_ERROR (int)
Error reporting constant
E_CORE_WARNING (int)
Error reporting constant
E_COMPILE_ERROR (int)
Error reporting constant
E_COMPILE_WARNING (int)
Error reporting constant
E_USER_ERROR (int)
Error reporting constant
E_USER_WARNING (int)
Error reporting constant
E_USER_NOTICE (int)
Error reporting constant
E_RECOVERABLE_ERROR (int)
Error reporting constant.
E_DEPRECATED (int)
Error reporting constant.
E_USER_DEPRECATED (int)
Error reporting constant.
E_ALL (int)
Error reporting constant
E_STRICT (int)
Error reporting constant
__COMPILER_HALT_OFFSET__ (int)
true (bool)
See Booleans.
false (bool)
See Booleans.
null (null)
See Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
A Windows CTRL+C event. Available as of PHP 7.4.0 (Windows only).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
A Windows CTRL+BREAK event. Available as of PHP 7.4.0 (Windows only).

See also: Magic constants.

Standard Predefined Constants

All constants from core extensions are defined in PHP by default.

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

}
?>


List of other reserved words

The following words cannot be used to name a class, interface or trait. Prior to PHP 8.0, they are also prohibited from being used in namespaces.

Reserved words
int | float | bool | string
true | false | null | void (as of PHP 7.1)
iterable (as of PHP 7.1) | object (as of PHP 7.2) | mixed (as of PHP 8.0) | never (as of PHP 8.1)

The following list of words have had soft reservations placed on them. Whilst they may still be used as class, interface, and trait names usage of them is highly discouraged since they may be used in future versions of PHP.

Soft reserved words
enum resource numeric

User Contributed Notes

There are no user contributed notes for this page.


List of Resource Types

The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.

Resource Types
Resource Type Name | Created By | Used By | Destroyed By | Definition
AddressInfo | socket_addrinfo_lookup() | socket_addrinfo_bind(), socket_addrinfo_connect(), socket_addrinfo_explain(), | None | AddressInfo (sockets extension)
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
cubrid connection | cubrid_connect() cubrid_connect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | cubrid_close() cubrid_disconnect() | Connection to CUBRID database
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() | Persistent connection to CUBRID database
cubrid request | cubrid_prepare() cubrid_execute() cubrid_query() cubrid_unbuffered_query() | cubrid_bind() cubrid_column_names() cubrid_column_types() cubrid_current_oid() cubrid_execute() cubrid_free_result() cubrid_get_query_timeout() cubrid_move_cursor() cubrid_next_result() cubrid_num_cols() cubrid_num_rows() cubrid_set_query_timeout() cubrid_data_seek() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_field() cubrid_fetch_lengths() cubrid_fetch_object() cubrid_fetch_row() cubrid_field_flags() cubrid_field_len() cubrid_field_name() cubrid_field_seek() cubrid_field_table() cubrid_field_type() cubrid_num_fields() cubrid_result() cubrid_lob2_bind() | cubrid_close_prepare() cubrid_close_request() | CUBRID request
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | None
cubrid lob2 | cubrid_lob2_new() cubrid_fetch() cubrid_fetch_row() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_object() | cubrid_lob2_export() cubrid_lob2_import() cubrid_lob2_read() cubrid_lob2_write() cubrid_lob2_tell() cubrid_lob2_tell64() cubrid_lob2_seek() cubrid_lob2_seek64() cubrid_lob2_size() cubrid_lob2_size64() | cubrid_lob2_close() | None
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | cURL handle
curl_multi | curl_multi_init() | curl_multi_errno(), curl_multi_exec(), curl_multi_info_read(), curl_multi_remove_handle(), curl_multi_select(), curl_multi_setopt() | curl_multi_close() | cURL multi handle
curl_share | curl_share_init() | curl_share_errno(), curl_share_setopt() | curl_share_close() | cURL share handle
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
enchant_broker | enchant_broker_init() | enchant_broker_describe(), enchant_broker_dict_exists(), enchant_broker_get_dict_path(), enchant_broker_get_error(), enchant_broker_list_dicts(), enchant_broker_set_dict_path(), enchant_broker_set_ordering() | enchant_broker_free() | Enchant broker (prior to PHP 8.0.0)
enchant_dict | enchant_broker_request_dict() enchant_broker_request_pwl_dict() | enchant_dict_add_to_personal(), enchant_dict_add_to_session(), enchant_dict_check(), enchant_dict_describe(), enchant_dict_get_error(), enchant_dict_is_in_session(), enchant_dict_store_replacement(), enchant_dict_suggest() | enchant_broker_free_dict() | Enchant dictionary (prior to 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 File
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 connection (prior to 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 (prior to PHP 8.0.0)
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD (prior to PHP 8.1.0)
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server (prior to PHP 8.1.0)
interbase blob | ibase_blob_create(), ibase_blob_import(), ibase_blob_open() | ibase_blob_add(), ibase_blob_cancel(), ibase_blob_echo(), ibase_blob_get(), ibase_blob_info() | ibase_blob_close()
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
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 connection (prior to PHP 8.1.0)
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result (prior to PHP 8.1.0)
ldap result entry | ldap result entry (prior to 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() | Link to MySQL database
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() | None | Persistent link to MySQL database
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 result
oci8 collection | oci_new_collection() | OCICollection::append(), OCICollection::assign(), OCICollection::assignElem(), OCICollection::getElem(), OCICollection::max(), OCICollection::size(), OCICollection::trim() | OCICollection::free() | Oracle Collection
oci8 connection | oci_connect(), oci_pconnect(), oci_new_connect() | oci_commit(), oci_error(), oci_new_cursor(), oci_parse(), oci_password_change(), oci_rollback(), oci_server_version(), oci_set_action(), oci_set_client_identifier(), oci_set_client_info(), oci_set_module_name() | oci_close() | Connection to Oracle Database
oci8 lob | oci_new_descriptor() | OCILob::append(), OCILob::close(), OCILob::eof(), OCILob::erase(), OCILob::export(), OCILob::flush(), OCILob::getBuffering(), OCILob::import(), OCILob::load(), OCILob::read(), OCILob::rewind(), OCILob::save(), OCILob::saveFile(), OCILob::seek(), OCILob::setBuffering(), OCILob::size(), OCILob::tell(), OCILob::truncate(), OCILob::write(), OCILob::writeTemporary(), OCILob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCILob::free() | Oracle large objects
oci8 statement | oci_parse(), oci_new_cursor() | oci_bind_array_by_name(), oci_bind_by_name(), oci_cancel(), oci_define_by_name(), oci_error() oci_execute(), oci_fetch_all(), oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row(), oci_fetch(), oci_field_is_null(), oci_field_name(), oci_field_precision(), oci_field_scale(), oci_field_size(), oci_field_type_raw(), oci_field_type(), oci_num_fields(), oci_num_rows(), oci_result(), oci_set_prefetch(), oci_statement_type() | oci_free_statement() | Oracle cursor
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() | Link to ODBC database
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() | None | Persistent link to ODBC database
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 result
birdstep link | Link to Birdstep database (prior to PHP 7.3.0)
birdstep result | Birdstep result (prior to PHP 7.3.0)
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
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 (prior to 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() | Link to PostgreSQL database (prior to 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() | None | Persistent link to PostgreSQL database
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 result (prior to 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() | None | pspell dictionary (prior to PHP 8.1.0)
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration (prior to PHP 8.1.0)
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Shared memory block handle (prior to PHP 8.0.0)
Socket | socket_accept(), socket_addrinfo_bind(), socket_addrinfo_connect(), socket_create(), socket_create_listen(), socket_import_stream(), socket_wsaprotocol_info_import() | socket_accept(), socket_bind(), socket_clear_error(), socket_connect(), socket_get_option(), socket_getpeername(), socket_getsockname(), socket_last_error(), socket_listen(), socket_read(), socket_recv(), socket_recvfrom(), socket_recvmsg(), socket_select(), socket_send(), socket_sendmsg(), socket_sendto(), socket_set_block(), socket_set_nonblock(), socket_set_option(), socket_shutdown(), socket_write(), socket_wsaprotocol_info_export(), socket_wsaprotocol_info_release() | socket_close() | Socket (sockets extension)
stream | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
SSH2 Session | ssh2_connect() | ssh2_disconnect()
SSH2 Listener | ssh2_forward_listen()
SSH2 SFTP | ssh2_sftp()
SSH2 Publickey Subsystem | ssh2_publickey_init()
sysvmsg queue | msg_get_queue() | msg_queue_exists(), msg_receive(), msg_send(), msg_set_queue(), msg_stat_queue() | msg_remove_queue() | System V Message Queue (prior to PHP 8.0.0)
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore (prior to PHP 8.0.0)
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory (prior to PHP 8.0.0)
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser (prior to PHP 8.0.0)
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file
zlib.deflate | deflate_init() | deflate_add() | None | incremental deflate context (prior to PHP 8.0.0)
zlib.inflate | inflate_init() | inflate_add(), inflate_get_read_len(), inflate_get_status() | None | incremental inflate context (prior to 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()


List of Available Filters

Table of Contents

  • String Filters
  • Conversion Filters
  • Compression Filters
  • Encryption Filters

The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.

It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.

For a list of filters installed in your version of PHP use stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.


String Filters

Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.

string.rot13

Use of this filter is equivalent to processing all stream data through the str_rot13() function.

Example #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs: Guvf vf n grfg. */
?>

string.toupper

Use of this filter is equivalent to processing all stream data through the strtoupper() function.

Example #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs: THIS IS A TEST. */
?>

string.tolower

Use of this filter is equivalent to processing all stream data through the strtolower() function.

Example #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs: this is a test. */
?>

string.strip_tags

Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.

Warning

This feature has been DEPRECATED as of PHP 7.3.0. Relying on this feature is highly discouraged.

Example #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);
/* Outputs: 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);
/* Outputs: bolded text enlarged to a level 1 heading */
?>

User Contributed Notes

There are no user contributed notes for this page.


Conversion Filters

Like the string.* filters, the convert.* filters perform actions similar to their names. For more information on a given filter, refer to the manual page for the corresponding function.

convert.base64-encode and convert.base64-decode

Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively. convert.base64-encode supports parameters given as an associative array. If line-length is given, the base64 output will be split into chunks of line-length characters each. If line-break-chars is given, each chunk will be delimited by the characters given. These parameters give the same effect as using base64_encode() with chunk_split().

Example #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);
/* Outputs: VGhpcyBpcyBhIHRlc3QuCg== */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs: VGhpcyBp
: cyBhIHRl
: c3QuCg== */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs: This is a test. */
?>

convert.quoted-printable-encode and convert.quoted-printable-decode

Use of the decode version of this filter is equivalent to processing all stream data through the quoted_printable_decode() function. There is no function equivalent to convert.quoted-printable-encode. convert.quoted-printable-encode supports parameters given as an associative array. In addition to the parameters supported by convert.base64-encode, convert.quoted-printable-encode also supports boolean arguments binary and force-encode-first. convert.base64-decode only supports the line-break-chars parameter as a type-hint for stripping from the encoded payload.

Example #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");
/* Outputs: =This is a test.=0A */
?>

convert.iconv.*

The convert.iconv.* filters are available, if iconv support is enabled, and their use is equivalent to processing all stream data with iconv(). These filters do not support parameters, but instead expect the input and output encodings to be given as part of the filter name, i.e. either as convert.iconv.<input-encoding>.<output-encoding> or convert.iconv.<input-encoding>/<output-encoding> (both notations are semantically equivalent).

Example #3 convert.iconv.*

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Outputs: This is a test. */
?>

User Contributed Notes

marcus at synchromedia dot co dot uk 10-May-2022 09:50
It's not quite obvious what all the available parameters are for convert.quoted-printable-encode. If you want the stream filter to act the same way as the quoted_printable_encode function, you need these extra params, for example:

stream_filter_append(
    STDOUT,
    'convert.quoted-printable-encode',
    STREAM_FILTER_WRITE,
    [
        'line-break-chars' => PHP_EOL,
        'line-length' => 75,
    ]
);
echo stream_copy_to_stream(STDIN, STDOUT);

Without these extra params set, you may get no wrapping at all, or wrapping using the wrong line break sequence.


Compression Filters

While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.

Note: Compression filters do not generate headers and trailers used by command line utilities such as gzip. They only compress and decompress the payload portions of compressed data streams.

zlib.deflate and zlib.inflate

zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in » RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.

Note: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).

zlib.* compression filters are available if zlib support is enabled.

Example #1 zlib.deflate and zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

*/
?>

Example #2 zlib.deflate simple

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

*/
?>

bzip2.compress and bzip2.decompress

bzip2.compress and bzip2.decompress work in the same manner as the zlib filters described above. The bzip2.compress filter accepts up to two parameters given as elements of an associative array: blocks is an integer value from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for workspace. work is also an integer value ranging from 0 to 250 indicating how much effort to expend using the normal compression method before falling back on a slower, but more reliable method. Tuning this parameter effects only compression speed. Neither size of compressed output nor memory usage are changed by this setting. A work factor of 0 instructs the bzip library to use an internal default. The bzip2.decompress filter only accepts one parameter, which can be passed as either an ordinary boolean value, or as the small element of an associative array. small, when set to a true value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.

bzip2.* compression filters are available if bz2 support is enabled.

Example #3 bzip2.compress and bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original file is 3288 bytes long.
The compressed file is 1488 bytes long.

*/
?>

User Contributed Notes

TingSong 20-Feb-2023 03:43
To decompress a gzipped stream:

<?php
$stream = fopen('https://example.com/some/file.txt.gz', 'rb');
stream_filter_append($stream, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15+16]);

// read the decompressed line directly
$line = fgets($stream);

// process the lines
?>

As the doc of zlib https://www.zlib.net/manual.html#Advanced

The 'window' parameter between 8 and 15 specified the window size from 2⁸ to 2¹⁵ 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);


Encryption Filters

Encryption filters are especially useful for file/stream encryption.

mcrypt.* and mdecrypt.*

Warning

This feature has been DEPRECATED as of PHP 7.1.0. Relying on this feature is highly discouraged.

mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:

mcrypt filter parameters
Parameter | Required? | Default | Sample Values
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules
iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher
key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher

Example #1 Encrypt/Decrypt with Blowfish

<?php
//$key assumed to be previously generated
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$fp = fopen('encrypted-file.enc', 'wb');
fwrite($fp, $iv);
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key);
stream_filter_append($fp, 'mcrypt.blowfish', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'message to encrypt');
fclose($fp);

//decrypt...
$fp = fopen('encrypted-file.enc', 'rb');
$iv = fread($fp, $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC));
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key)
stream_filter_append($fp, 'mdecrypt.blowfish', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));//trims off null padding
fclose($fp);
echo $data;
?>

Example #2 Encrypt file using AES-128 CBC with SHA256 HMAC

<?php
AES_CBC::encryptFile($password, "plaintext.txt", "encrypted.enc");
AES_CBC::decryptFile($password, "encrypted.enc", "decrypted.txt");

class AES_CBC
{
protected static $KEY_SIZES = array('AES-128'=>16,'AES-192'=>24,'AES-256'=>32);
protected static function key_size() { return self::$KEY_SIZES['AES-128']; } //default AES-128
public static function encryptFile($password, $input_stream, $aes_filename){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fin = fopen($input_stream, "rb");
$fc = fopen($aes_filename, "wb+");
if (!empty($fin) && !empty($fc)) {
fwrite($fc, str_repeat("_", 32) );//placeholder, SHA256 HMAC will go here later
fwrite($fc, $hmac_salt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $esalt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
$infilesize = 0;
while (!feof($fin)) {
$block = fread($fin, 8192);
$infilesize+=strlen($block);
fwrite($fc, $block);
}
$block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $block_size - ($infilesize % $block_size);//$padding is a number from 1-16
fwrite($fc, str_repeat(chr($padding), $padding) );//perform PKCS7 padding
fclose($fin);
fclose($fc);
$hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb+");
fwrite($fc, $hmac_raw);//overwrite placeholder
fclose($fc);
}
}
public static function decryptFile($password, $aes_filename, $out_stream) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$hmac_raw = file_get_contents($aes_filename, false, NULL, 0, 32);
$hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
$hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb");
$fout = fopen($out_stream, 'wb');
if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
fread($fc, 32+$iv_size);//skip sha256 hmac and salt
$esalt = fread($fc, $iv_size);
$iv = fread($fc, $iv_size);
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fc)) {
$block = fread($fc, 8192);
if (feof($fc)) {
$padding = ord($block[strlen($block) - 1]);//assume PKCS7 padding
$block = substr($block, 0, 0-$padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2) {
if(strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
static $init=0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped=0;
function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped<32){
$outlen = min($bucket->datalen,32-$this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen-$outlen;
$this->skipped+=$outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}

User Contributed Notes

Maarten Bodewes 06-Aug-2017 12:21
The examples on this page should be destroyed with utmost urgency.

Strangely most people will fall over the use of generating the IV and 3DES key using MD5, a weak hash function, e.g. the previous note and CryptoFails blog.

http://www.cryptofails.com/post/70059608390/php-documentation-woes

A password based key derivation function should be used (bcrypt, PBKDF2).

However the use of MD-5 for key derivation however isn't that bad and if the password is strong enough (it usually isn't) then the generated DES ABC key is strong enough even now.

Using an identical IV for each password means that this function directly leaks information about the encrypted file. If the start of two encrypted files is identical then this function will directly leak information. For instance, if the routine encrypts multiple images then the JPEG header would be easily distinguished.

All in all these examples use deprecated routines (mcrypt), deprecated cryptographic functions (MD5 / DES) and then incorrectly perform the actual encryption. Enough reason to destroy them in the first place.
Uwe Ohse 22-Feb-2017 04:17
1) The mcrypt module has been deprecated with PHP 7.1.
What does that mean for the encryption filters?

2) deriving the IV from the secret passphrase seems wrong. This leaks information about the passphrase without need.

3) using md5() for this? Really? hash() has been available since PHP 5.1.2.

4) hashing the passphrase twice does not add any security.

5) using substr() on binary data (why, oh why, is true passed to md5()?) might lead to headaches if mbstring.func_overload is used.


List of Supported Socket Transports

Table of Contents

  • Internet Domain: TCP, UDP, SSL, and TLS
  • Unix Domain: Unix and UDG

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().

User Contributed Notes

alefinvest at outlook dot com 06-Aug-2021 06:47
That was hard to fetch this page mentioned in note by other user long time ago.
I intended to read Appendix P to find some code examples.
Wondering how to implement custom transport extension for php on our server tto be used with some nowadays technologies research.
https://www.php.net/manual/ru/function.stream-context-create.php#75211


Internet Domain: TCP, UDP, SSL, and TLS

ssl://, tls://, sslv2:// & sslv3://.

Note: If no transport is specified, tcp:// will be assumed.

  • 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 expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Note: IPv6 numeric addresses with port numbers
In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption.

ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.

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

unix:// and udg://.

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.

Note: Unix domain sockets are not supported on Windows.

User Contributed Notes

Matthew Fortune 16-Feb-2007 03:03
It appears that fsockopen prior to php5 did not need the unix:// qualifier when opening a unix domain socket:

php4: fsockopen("/tmp/mysocket"......);

php5: fsockopen("unix:///tmp/mysocket"......);

This caught me out when upgrading.


PHP type comparison tables

The following tables demonstrate behaviors of PHP types and comparison operators, for both loose and strict comparisons. This supplemental is also related to the manual section on type juggling. Inspiration was provided by various user comments and by the work over at » BlueShoes.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an int. false is a bool while "false" is a string.

Note:

HTML Forms do not pass integers, floats, or booleans; they pass strings. To find out if a string is numeric, you may use is_numeric().

Note:

Simply doing if ($x) while $x is undefined will generate an error of level E_NOTICE. Instead, consider using empty() or isset() and/or initialize your variables.

Note:

Some numeric operations can result in a value represented by the constant NAN. Any loose or strict comparisons of this value against any other value, including itself, but except true, will have a result of false. (i.e. NAN != NAN and NAN !== NAN) Examples of operations that produce NAN include sqrt(-1), asin(2), and acosh(0).

Comparisons of $x with PHP functions
Expression | gettype() | empty() | is_null() | isset() | bool : if($x)
$x = ""; | string | true | false | true | false
$x = null; | NULL | true | true | false | false
var $x; | NULL | true | true | false | false
$x is undefined | NULL | true | true | false | false
$x = []; | array | true | false | true | false
$x = ['a', 'b']; | array | false | false | true | true
$x = false; | bool | true | false | true | false
$x = true; | bool | false | false | true | true
$x = 1; | int | false | false | true | true
$x = 42; | int | false | false | true | true
$x = 0; | int | true | false | true | false
$x = -1; | int | false | false | true | true
$x = "1"; | string | false | false | true | true
$x = "0"; | string | true | false | true | false
$x = "-1"; | string | false | false | true | true
$x = "php"; | string | false | false | true | true
$x = "true"; | string | false | false | true | true
$x = "false"; | string | false | false | true | true

Loose comparisons with ==
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "php" | ""
true | true | false | true | false | true | true | false | true | false | false | true | false
false | false | true | false | true | false | false | true | false | true | true | false | true
1 | true | false | true | false | false | true | false | false | false | false | false | false
0 | false | true | false | true | false | false | true | false | true | false | false* | false*
-1 | true | false | false | false | true | false | false | true | false | false | false | false
"1" | true | false | true | false | false | true | false | false | false | false | false | false
"0" | false | true | false | true | false | false | true | false | false | false | false | false
"-1" | true | false | false | false | true | false | false | true | false | false | false | false
null | false | true | false | true | false | false | false | false | true | true | false | true
[] | false | true | false | false | false | false | false | false | true | true | false | false
"php" | true | false | false | false* | false | false | false | false | false | false | true | false
"" | false | true | false | false* | false | false | false | false | true | false | false | true
* true prior to PHP 8.0.0.

Strict comparisons with ===
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "php" | ""
true | true | false | false | false | false | false | false | false | false | false | false | false
false | false | true | false | false | false | false | false | false | false | false | false | false
1 | false | false | true | false | false | false | false | false | false | false | false | false
0 | false | false | false | true | false | false | false | false | false | false | false | false
-1 | false | false | false | false | true | false | false | false | false | false | false | false
"1" | false | false | false | false | false | true | false | false | false | false | false | false
"0" | false | false | false | false | false | false | true | false | false | false | false | false
"-1" | false | false | false | false | false | false | false | true | false | false | false | false
null | false | false | false | false | false | false | false | false | true | false | false | false
[] | false | false | false | false | false | false | false | false | false | true | false | false
"php" | false | false | false | false | false | false | false | false | false | false | true | false
"" | false | false | false | false | false | false | false | false | false | false | false | true

User Contributed Notes

Jeroen 14-Jul-2023 04:26
Be aware of the difference between checking the *value* of an array item, and checking the *existence* of an array item:
<?php
$arr = [
  'x' => 0,
  'y' => null,
];

isset($arr['x']); // true, same as isset(0)
isset($arr['y']); // false, same as isset(null)

array_key_exists('y', $arr); // true, though the value is null
array_key_exists('z', $arr); // false
ray dot paseur at SometimesUsesGmail dot com 14-Feb-2023 11:37
A colorized version of the loose comparison table is here (no copyright, nor attribution required)
https://iconoun.com/php_type_comparisons.php
Anonymous 17-Nov-2020 02:24
I noticed that some "magic" also happens when comparing strings with leading zeros with only two equal signs:

<?php
var_dump('1' == '01');
var_dump('01' == '000001');
?>

Output:
bool(true)
bool(true)

If the string contains only numbers all leading zeroes seem to be ignored.
TrickyFoxy 02-Jan-2020 08:25
<?php
echo md5('240610708') == md5('QNKCDZO') ? "equal" : "not equal"; // prints equal!!!
php at ckls dot net 20-Aug-2018 02:50
regarding the editors note in php at richardneill dot org note:
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

While this is true, there is still the following behaviour:
<?php
$x = "1";
$y = "+1";
var_dump($x == $x);
?>
outputs "bool(true)".
So still be wary of string-comparison where both strings might be interpreted as numbers.
mark at theanti dot social 29-Mar-2018 08:59
There is also 0.0 which is not identical to 0.

  $x = 0.0;
  gettype($x); // double
  empty($x); // true
  is_null($x); //false
  isset($x); // true
  is_numeric($x); // true
  $x ? true : false; // false
  $x == 0; // true
  $x == "0"; // true
  $x == "0.0"; // true
  $x == false; // true
  $x == null; // true
  $x === 0; // false
  $x === false; // false
  $x === null; // false
  $x === "0"; // false
  $x === "0.0"; // false
alt dot jl-3gi8b7l at binich dot com 10-Mar-2018 03:41
Here's how PHP handles loose and strict comparisons of default parameters in functions:

Very unintuitive:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return $x; // returns 0 !!
    }

echo f(0);
?>

Here some further tests:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return 'A:'.$x;
    if ($x === 'surprise')
        return 'B:'.$x;
    return 'C:'.$x;
    }

echo "\n".f(0); // A:0 !!
echo "\n".f(0.0); // A:0 !!
echo "\n".f(NULL); // C: !!
echo "\n".f(FALSE); // C:
echo "\n".f(); // A:surprise
echo "\n".f(''); // C:
echo "\n".f((integer)0); // A:0
echo "\n".f((string)0); // C:0
echo "\n".f('0'); // C:0
echo "\n".f(0.1); // C:0.1
echo "\n".f(array()); // C:Array
echo "\n".f('surprise'); // A:surprise
?>
biziclop at vipmail dot hu 12-Aug-2017 08:57
Want to strictly compare integers that may or may not be converted to floats (via PHPExcel import/export, etc.)? You are out of luck:

var_dump(   (int)1 ===   (int)1 ); // bool(true)
var_dump( (float)1 === (float)1 ); // bool(true)
var_dump( (float)1 ===   (int)1 ); // bool(false)
var_dump(   (int)1 === (float)1 ); // bool(false)

This slightly complicated function might help you:

function equal_numbers( $a, $b ){
  if( $a === $b )  return true;
  if(   is_int( $a ) && is_float( $b ))  return (float)$a === $b && $a ===   (int)$b;
  if( is_float( $a ) &&   is_int( $b ))  return   (int)$a === $b && $a === (float)$b;
  return false;
}

Here are some tests:

test(100, 100.0 ); // int(100) float(100) bool(true)
test(  0,  -0   ); // int(0)   int(0)     bool(true)
test( -0,  -0.0 ); // int(0)   float(-0)  bool(true)
test(  0, 1/0   ); // int(0)   float(INF) bool(false)
test(  0, acos(2));// int(0)   float(NAN) bool(false)
test(       PHP_INT_MAX * 10, 0 );             //float(92233720368547758080) int(0) bool(false)
test((float)PHP_INT_MAX,     PHP_INT_MAX     );//float(9223372036854775808)  int(9223372036854775807) bool(false)
test((float)PHP_INT_MAX / 2, PHP_INT_MAX / 2 );//float(4611686018427387904)  float(4611686018427387904) bool(true)

function test( $a, $b ){
  var_dump( $a, $b, equal_numbers( $a, $b ));
}
engineer dot morozov at gmail dot com 07-Feb-2016 03:23
If you want to calculate how much more/less items by the criterion

Example:

in loop:
$counter += intval($item->isValid()) <=> 0.5;

if $counter >= 0 - valid items are more then invalid on $counter
if $counter  < 0 - valid items are less then invalid on $counter
trexx68 25-Apr-2015 05:11
If you want to view the truth tables colorized, just:

1. Save a local copy of this page as an .html file,
2. View the page source with any text editor.
3. Replace the opening <head> tag so it will include this:

<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

4. Replace the closing </body> tag with this:

  <script>
    $( "td:contains('FALSE')" ).css("color", "red");
    $( "td:contains('TRUE')" ).css("color", "green");
  </script>
</body>

5. Save the file, and view it on your browser.  Enjoy.
aravind dot a dot padmanabhan at gmail dot com 22-Apr-2015 02:31
please note that

$x = 0.0 ;
print empty($x); // returns 1 (true)

$x = "0.0";
print empty($x); // returns blank (false);
Anonymous 16-Oct-2014 06:19
The loose comparison chart is missing a few things.

array(1)==true returns true.

also:

(int)array(1) === 1 returns true

This is symmetric:

array(1) === (array)1 returns true

but the loose comparison

array(1)==1 still returns false.
blue dot hirano at gmail dot com 07-Sep-2014 02:29
The truth tables really ought to be colorized; they're very hard to read as they are right now (just big arrays of TRUE and FALSE).

Also, something to consider: clustering the values which compare similarly (like is done on qntm.org/equality) would make the table easier to read as well. (This can be done simply by hand by rearranging the order of headings to bring related values closer together).
Anonymous 21-Nov-2013 01:43
I'm running PHP 5.5.3.

This is a correction to one of the previous posts.

<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>

Output is:

true, false, false
crazy888s at hotmail dot com 14-Dec-2012 06:14
PHP's loose comparisons can be a huge convenience when used properly! It's extremely helpful to just remember the following are always FALSE:

null, false, "", 0, "0", array()

If your application never depends on a particular "empty/false/null/0/not set" value type, you won't have to worry about 99% of the other weird cases listed here. You won't need empty() or isset(). And ALL variable types will always work as expected for statements like:

if(boolean && !string){...}
if(array){...}
if(!null || int){...}

Consider the same when working with your database values.
php at richardneill dot org 12-Apr-2012 07:45
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.


List of Parser Tokens

Various parts of the PHP language are represented internally by tokens. A code snippet that contains an invalid sequence of tokens may lead to errors like Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10." where token == is internally represented by T_IS_EQUAL.

The following table lists all tokens. They are also available as PHP constants.

Note: Usage of T_* constants

T_* constants values are automatically generated based on PHP's underlying parser infrastructure. This means that the concrete value of a token may change between two PHP versions. This means that your code should never rely directly on the original T_* values taken from PHP version X.Y.Z, to provide some compatibility across multiple PHP versions.

To make use of T_* constants across multiple PHP versions, undefined constants may be defined by the user (using big numbers like 10000) with an appropriate strategy that will work with both PHP versions and T_* values.

<?php
// Prior to PHP 7.4.0, T_FN is not defined.
defined('T_FN') || define('T_FN', 10001);

Tokens
Token | Syntax | Reference
T_ABSTRACT | abstract | Class Abstraction
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG | & | Type declarations (available as of PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG | & | Type declarations (available as of PHP 8.1.0)
T_AND_EQUAL | &= | assignment operators
T_ARRAY | array() | array(), array syntax
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_ATTRIBUTE | #[ | attributes (available as of PHP 8.0.0)
T_BAD_CHARACTER |  | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d) (available as of PHP 7.4.0)
T_BOOLEAN_AND | && | logical operators
T_BOOLEAN_OR | || | logical operators
T_BOOL_CAST | (bool) or (boolean) | type-casting
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Exceptions
T_CLASS | class | classes and objects
T_CLASS_C | __CLASS__ | magic constants
T_CLONE | clone | classes and objects
T_CLOSE_TAG | ?> or %> | escaping from HTML
T_COALESCE | ?? | comparison operators
T_COALESCE_EQUAL | ??= | assignment operators (available as of PHP 7.4.0)
T_COMMENT | // or #, and /* */ | comments
T_CONCAT_EQUAL | .= | assignment operators
T_CONST | const | class constants
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | complex variable parsed syntax
T_DEC | -- | incrementing/decrementing operators
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | magic constants
T_DIV_EQUAL | /= | assignment operators
T_DNUMBER | 0.12, etc. | floating point numbers
T_DO | do | do..while
T_DOC_COMMENT | /** */ | PHPDoc style comments
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax
T_DOUBLE_ARROW | => | array syntax
T_DOUBLE_CAST | (real), (double) or (float) | type-casting
T_DOUBLE_COLON | :: | see T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO | echo | echo
T_ELLIPSIS | ... | function arguments
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | constant part of string with variables
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 (available as of PHP 8.1.0)
T_END_HEREDOC |  | heredoc syntax
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, classes and objects
T_FILE | __FILE__ | magic constants
T_FINAL | final | Final Keyword
T_FINALLY | finally | Exceptions
T_FN | fn | arrow functions (available as of PHP 7.4.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function | functions
T_FUNC_C | __FUNCTION__ | magic constants
T_GLOBAL | global | variable scope
T_GOTO | goto | goto
T_HALT_COMPILER | __halt_compiler() | __halt_compiler
T_IF | if | if
T_IMPLEMENTS | implements | Object Interfaces
T_INC | ++ | incrementing/decrementing operators
T_INCLUDE | include | include
T_INCLUDE_ONCE | include_once | include_once
T_INLINE_HTML |  | text outside PHP
T_INSTANCEOF | instanceof | type operators
T_INSTEADOF | insteadof | Traits
T_INTERFACE | interface | Object Interfaces
T_INT_CAST | (int) or (integer) | type-casting
T_ISSET | isset() | isset()
T_IS_EQUAL | == | comparison operators
T_IS_GREATER_OR_EQUAL | >= | comparison operators
T_IS_IDENTICAL | === | comparison operators
T_IS_NOT_EQUAL | != or <> | comparison operators
T_IS_NOT_IDENTICAL | !== | comparison operators
T_IS_SMALLER_OR_EQUAL | <= | comparison operators
T_LINE | __LINE__ | magic constants
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | integers
T_LOGICAL_AND | and | logical operators
T_LOGICAL_OR | or | logical operators
T_LOGICAL_XOR | xor | logical operators
T_MATCH | match | match (available as of PHP 8.0.0)
T_METHOD_C | __METHOD__ | magic constants
T_MINUS_EQUAL | -= | assignment operators
T_MOD_EQUAL | %= | assignment operators
T_MUL_EQUAL | *= | assignment operators
T_NAMESPACE | namespace | namespaces
T_NAME_FULLY_QUALIFIED | \App\Namespace | namespaces (available as of PHP 8.0.0)
T_NAME_QUALIFIED | App\Namespace | namespaces (available as of PHP 8.0.0)
T_NAME_RELATIVE | namespace\Namespace | namespaces (available as of PHP 8.0.0)
T_NEW | new | classes and objects
T_NS_C | __NAMESPACE__ | namespaces
T_NS_SEPARATOR | \ | namespaces
T_NUM_STRING | "$a[0]" | numeric array index inside string
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | classes and objects
T_NULLSAFE_OBJECT_OPERATOR | ?-> | classes and objects
T_OPEN_TAG | <?php, <? or <% | escaping from HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML
T_OR_EQUAL | |= | assignment operators
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Also defined as T_DOUBLE_COLON.
T_PLUS_EQUAL | += | assignment operators
T_POW | ** | arithmetic operators
T_POW_EQUAL | **= | assignment operators
T_PRINT | print | print
T_PRIVATE | private | classes and objects
T_PROTECTED | protected | classes and objects
T_PUBLIC | public | classes and objects
T_READONLY | readonly | classes and objects (available as of PHP 8.1.0)
T_REQUIRE | require | require
T_REQUIRE_ONCE | require_once | require_once
T_RETURN | return | returning values
T_SL | << | bitwise operators
T_SL_EQUAL | <<= | assignment operators
T_SPACESHIP | <=> | comparison operators
T_SR | >> | bitwise operators
T_SR_EQUAL | >>= | assignment operators
T_START_HEREDOC | <<< | heredoc syntax
T_STATIC | static | variable scope
T_STRING | parent, self, etc. | identifiers, e.g. keywords like parent and self, function names, class names and more are matched. See also T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME | "${a | complex variable parsed syntax
T_SWITCH | switch | switch
T_THROW | throw | Exceptions
T_TRAIT | trait | Traits
T_TRAIT_C | __TRAIT__ | __TRAIT__
T_TRY | try | Exceptions
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | type-casting
T_USE | use | namespaces
T_VAR | var | classes and objects
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | assignment operators
T_YIELD | yield | generators
T_YIELD_FROM | yield from | generators

See also token_name().

User Contributed Notes

fgm at osinet dot fr 22-Sep-2008 01:08
T_ENCAPSED_AND_WHITESPACED is returned when parsing strings with evaluated content, like "some $value" or this example from the Strings reference page:

<?php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

This last example is tokenized as:
T_ECHO
  echo
T_WHITESPACE
  %20 (a space character)
T_START_HEREDOC
  <<
T_ENCAPSED_AND_WHITESPACE
  My name is "
T_VARIABLE
  $name
T_ENCAPSED_AND_WHITESPACE
  ". I am printing some
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  foo
T_ENCAPSED_AND_WHITESPACE
  . Now, I am printing some
T_CURLY_OPEN
  {
T_VARIABLE
  $foo
T_OBJECT_OPERATOR
  ->
T_STRING
  bar
(terminal)
  [
T_LNUMBER
  1
(terminal)
  ]
(terminal)
  }
T_ENCAPSED_AND_WHITESPACE
  . This should print a capital 'A': \x41
T_END_HEREDOC
  EOT
(terminal)
  ;
nathan at unfinitydesign dot com 22-Sep-2008 05:52
T_ENCAPSED_AND_WHITESPACE is whitespace which intersects a group of tokens. For example, an "unexpected T_ENCAPSED_AND_WHITESPACE" error is produced by the following code:

<?php
$main_output_world = 'snakes!';
echo('There are' 10 $main_output_world);
?>

Note the missing concatenation operator between the two strings leads to the whitespace error that is so named above. The concatenation operator instructs PHP to ignore the whitespace between the two code tokens (the so named "encapsed" data"), rather than parse it as a token itself.

The correct code would be:

<?php
$main_output_world = 'snakes!';
echo('There are' . 10 . $main_output_world);
?>

Note the addition of the concatenation operator between each token.


Userland Naming Guide

Table of Contents

  • Global Namespace
  • Rules
  • Tips

The following is a guide for how to best choose names for identifiers in userland PHP code. When choosing names for any code that creates symbols in the global namespace, it is important to take into account the following guidelines to prevent future versions of PHP from clashing with your symbols.

User Contributed Notes

There are no user contributed notes for this page.


Global Namespace

Here is an overview of code constructs that go into the global namespace:

  • functions

  • classes

  • interfaces

  • constants (not class constants)

  • variables defined outside of functions/methods

User Contributed Notes

There are no user contributed notes for this page.


Rules

The following list gives an overview of which rights the PHP project reserves for itself, when choosing names for new internal identifiers. The definitive guide is the official » CODING STANDARDS:

  • PHP owns the top-level namespace but tries to find decent descriptive names and avoid any obvious clashes.

  • Function names use underscores between words, while class names use both the camelCase and PascalCase rules.

  • PHP will prefix any global symbols of an extension with the name of the extension. (In the past, there have been numerous exceptions to this rule.) Examples:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (example of a past mistake)

    • new SplFileObject()

  • Iterators and Exceptions are however simply postfixed with "Iterator" and "Exception." Examples:

    • ArrayIterator

    • LogicException

  • PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality. Examples:

    • __get()

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


Tips

In order to write future-proof code, it is recommended that you don't place many variables, functions or classes in the global namespace. This will prevent naming conflicts with 3rd party code as well as possible future additions to the language.

One common way to prevent naming conflicts of functions and classes is to add them to their own dedicated namespace.

<?php

namespace MyProject;

function my_function() {
return true;
}

\MyProject\my_function();

This still needs you to keep track of already used namespaces, but once you have decided on a namespace you will be using you can add all functions and classes to it without having to think about conflicts again.

It is considered best practice to limit the number of variables added to the global scope in order to prevent naming conflicts with 3rd party code.

Note: Variable scoping

Because of PHP's scoping rules variables defined inside functions and methods are not in the global scope and as such cannot conflict with other variables defined in the global scope.

User Contributed Notes

There are no user contributed notes for this page.


About the manual

Table of Contents

  • Formats
  • About user notes
  • How to read a function definition (prototype)
  • PHP versions documented in this manual
  • How to find more information about PHP
  • How to help improve the documentation
  • How we generate the formats
  • Translations

User Contributed Notes

There are no user contributed notes for this page.


Formats

The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.

Note:

Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.

The manual can be read online at the » PHP.net website. The online version of the PHP manual has currently two CSS stylesheets, web friendly and a printer-friendly stylesheet.

Two notable advantages of the online manual over most of the offline formats is the integration of user-contributed notes and the » URL shortcuts that may be used to get to the desired manual parts quickly. An obvious disadvantage is the requirement to be online to view this edition of the manual.

There are several offline formats of the manual, and the most appropriate format for depends on the operating system, and personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.

The most cross-platform format of the manual is the HTML version. This is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). We provide these versions compressed, so a decompression utility is required to retrieve the files contained within the archives.

For Windows platforms, the Windows HTML Help version of the manual enhances the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access. CHM viewers for Linux desktops are also available. Check out » xCHM or » GnoCHM.

There is also an » extended CHM version available, which is updated less frequently, but provides many additional features. It will only work on Microsoft Windows though, because of the technologies used to build the help pages.

User Contributed Notes

There are no user contributed notes for this page.


About user notes

The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they may be viewed in their submitted form online, and in some of the offline formats.

Note:

The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)

Note:

For the purposes of license coverage the user-contributed notes are considered part of the PHP manual, and are therefore covered by the same license that covers this documentation (Creative Commons Attribution at the moment). For more details see the Manual's Copyright page.

User Contributed Notes

There are no user contributed notes for this page.


How to read a function definition (prototype)

Each function in the manual is documented for quick reference. Knowing how to read and understand the text will make learning PHP much easier. Rather than relying on examples or cut/paste, everyone should know how to read function definitions (prototypes). Let's begin:

Note: Prerequisite: Basic understanding of types

Although PHP is a loosely typed language, it's important to have a basic understanding of types as they have important meaning.

Function definitions tell us what type of value is returned. Let's use the definition for strlen() as our first example:

strlen

(PHP 4, PHP 5, PHP 7)
strlen -- Get string length

Description
strlen ( string $string ) : int

Returns the length of given string.

Explanation of a function definition
Part | Description
strlen | The function name.
(PHP 4, PHP 5, PHP 7) | strlen() has been around in all versions of PHP 4, 5 and 7
( string $string ) | The first (and in this case the only) parameter/argument for this function is named string, and it's a string.
int | Type of value this function returns, which is an int (i.e. the length of a string is measured in numbers).

We could rewrite the above function definition in a generic way:

      function name    ( parameter type   parameter name ) : returned type

Many functions take on multiple parameters, such as in_array(). Its prototype is as follows:

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

What does this mean? in_array() returns a boolean value, true on success (if the needle was found in the haystack) or false on failure (if the needle was not found in the haystack). The first parameter is named needle and it can be of many different types, so we call it "mixed". This mixed needle (what we're looking for) can be either a scalar value (string, integer, or float), or an array. haystack (the array we're searching in) is the second parameter. The third optional parameter is named strict. All optional parameters have default values; if the default value is unknown, it is shown as ?. The manual states that the strict parameter defaults to boolean false. See the manual page on each function for details on how they work.

In addition the & (ampersand) symbol prepended to a function parameter allows the parameter to be passed by reference, as seen below:

       preg_match ( string $pattern , string $subject , array &$matches = null,
       int $flags = 0 , int $offset = 0 ) : int|false

In this example, we can see the third optional parameter &$matches will be passed as reference.

There are also functions with more complex PHP version information. Take html_entity_decode() as an example:

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

This means that this function has only been available in a released version since PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


PHP versions documented in this manual

The manual contains information about past, current, and future versions of PHP. Changes in behaviour are documented as notes, changelogs, and inline text within the manual pages. The earliest documented version is PHP 7.0.0.

When documentation exists for the latest (unreleased) developmental versions of PHP, it will be labeled as either "available in Git" or "development version." And while these changes should be planned for, in rare cases they may change.

All development takes place in Git and may be checked out as described within the » anonymous Git access page.

And to clarify, the manual will refer to major, minor and point PHP releases. Using PHP 7.3.1 as an example, the 7 refers to the major version, 3 to minor, and 1 is the point release. Typically PHP only adds new features to major and minor releases, and fixes bugs in point releases. However, this convention is not always true.

Also note that the PHP manual is written in present tense, not future tense, even for documented features that are not yet available. The reason for this is so the manual can stand the test of time, thus not require tedious grammar updates with every PHP release.

Many times the PHP manual lists "Default Values" for PHP directives. These values are based on how PHP behaves without a php.ini configuration file, so this may differ from values found in the distributed php.ini-development and php.ini-production files. They also refer to the latest version of PHP, although changelog entries do mention past values. See the PHP directive appendix for details regarding these values and changes.

User Contributed Notes

There are no user contributed notes for this page.


How to find more information about PHP

This manual does not attempt to provide instruction about general programming practices. First-time - or even just beginning - programmers may find it difficult to learn how to program in PHP using this manual exclusively. Instead, seek out a text more oriented towards beginners.

There are a number of active mailing lists for discussion on all aspects of programming with PHP. If stuck with a problem, consider using these lists. For support options, including mailing lists, view » the PHP.net support page.

User Contributed Notes

There are no user contributed notes for this page.


How to help improve the documentation

There are several ways everyone can help improve this documentation.

If an error is found in this manual, in any language, please report them using the issue tracker of the respective language repository at » https://github.com/php; for instance, errors in the English manual should be reported at » https://github.com/php/doc-en/issues. All documentation related problems, including those about manual formats, should be submitted as bug reports.

Note:

Please don't abuse the issue trackers by submitting requests for help. Instead, use one of the many » support options.

By contributing notes, users may provide additional examples, caveats, and clarifications for other readers. But please do not submit bug reports using the annotation system. For details, see the section titled 'About user notes'.

It is also possible to submit pull requests to the » Github mirror of the documentation repository.

The PHP manual is translated into many languages. Knowing English and a foreign language allows for another way to help improve the PHP manual by working with a translation team. For information about starting a new translation, or helping a currently translated version, please read » http://doc.php.net/tutorial/.

The PHP Documentation Project also has an IRC channel where many manual authors hang out. Stop by #php.doc on irc.efnet.org and discuss ways to improve the PHP documentation.

User Contributed Notes

There are no user contributed notes for this page.


How we generate the formats

This manual is written in XML using the » DocBook XML DTD, using » PhD (The [PH]P based [D]ocBook renderer) for maintenance and formatting.

Using XML as a source format gives the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tool used for formatting the online manual is » PhD. We use » Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.

The PHP manual is generated in various languages and formats, see » https://www.php.net/docs.php for additional details. The XML source code may be downloaded from git and viewed at » https://github.com/php/doc-en.

User Contributed Notes

There are no user contributed notes for this page.


Translations

The PHP manual is available not only in various formats, but also in various languages. The text of the manual is first written in English, then teams of people across the world take care of translating it to their native languages. If a translation for a specified function or chapter has not yet been made, the manual's build system falls back to the English version of it.

People involved in the translations start from the XML source code available from » https://github.com/php/doc-en and from it they translate to their mother language. They do not use the generated versions (like HTML or plain text) as it's the build system that takes care of the conversions from XML to human readable formats.

Note:

To help translate the documentation, please get in touch with the translation/documentation team by subscribing to the phpdoc mailing list: send an empty mail to » phpdoc-subscribe@lists.php.net. The mailing list address is phpdoc@lists.php.net. State in the message an interest in translating the manual and someone will reply with feedback on moving forward by helping start a new language translation, or by contacting the existing team for the desired language.

At the moment the manual is available, partly or not, in over 10 languages.

They may all be downloaded here: » 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.


Index listing

Table of Contents

  • Function and Method listing
  • Example listing

User Contributed Notes

There are no user contributed notes for this page.


Function and Method listing

List of all the functions and methods in the manual

a b c d e f g h i j k l m n o p q r s t u v w x y z _

  • a
    • abs - Absolute value
    • acos - Arc cosine
    • acosh - Inverse hyperbolic cosine
    • addcslashes - Quote string with slashes in a C style
    • addslashes - Quote string with slashes
    • AllowDynamicProperties::__construct - Construct a new AllowDynamicProperties attribute instance
    • apache_child_terminate - Terminate apache process after this request
    • apache_getenv - Get an Apache subprocess_env variable
    • apache_get_modules - Get a list of loaded Apache modules
    • apache_get_version - Fetch Apache version
    • apache_lookup_uri - Perform a partial request for the specified URI and return all info about it
    • apache_note - Get and set apache request notes
    • apache_request_headers - Fetch all HTTP request headers
    • apache_response_headers - Fetch all HTTP response headers
    • apache_setenv - Set an 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 - Create an array
    • ArrayAccess::offsetExists - Whether an offset exists
    • ArrayAccess::offsetGet - Offset to retrieve
    • ArrayAccess::offsetSet - Assign a value to the specified offset
    • ArrayAccess::offsetUnset - Unset an offset
    • 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 - Changes the case of all keys in an array
    • array_chunk - Split an array into chunks
    • array_column - Return the values from a single column in the input array
    • array_combine - Creates an array by using one array for keys and another for its values
    • array_count_values - Counts the occurrences of each distinct value in an array
    • array_diff - Computes the difference of arrays
    • array_diff_assoc - Computes the difference of arrays with additional index check
    • array_diff_key - Computes the difference of arrays using keys for comparison
    • array_diff_uassoc - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey - Computes the difference of arrays using a callback function on the keys for comparison
    • array_fill - Fill an array with values
    • array_fill_keys - Fill an array with values, specifying keys
    • array_filter - Filters elements of an array using a callback function
    • array_flip - Exchanges all keys with their associated values in an array
    • array_intersect - Computes the intersection of arrays
    • array_intersect_assoc - Computes the intersection of arrays with additional index check
    • array_intersect_key - Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc - Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey - Computes the intersection of arrays using a callback function on the keys for comparison
    • array_is_list - Checks whether a given array is a list
    • array_keys - Return all the keys or a subset of the keys of an array
    • array_key_exists - Checks if the given key or index exists in the array
    • array_key_first - Gets the first key of an array
    • array_key_last - Gets the last key of an array
    • array_map - Applies the callback to the elements of the given arrays
    • array_merge - Merge one or more arrays
    • array_merge_recursive - Merge one or more arrays recursively
    • array_multisort - Sort multiple or multi-dimensional arrays
    • array_pad - Pad array to the specified length with a value
    • array_pop - Pop the element off the end of array
    • array_product - Calculate the product of values in an array
    • array_push - Push one or more elements onto the end of array
    • array_rand - Pick one or more random keys out of an array
    • array_reduce - Iteratively reduce the array to a single value using a callback function
    • array_replace - Replaces elements from passed arrays into the first array
    • array_replace_recursive - Replaces elements from passed arrays into the first array recursively
    • array_reverse - Return an array with elements in reverse order
    • array_search - Searches the array for a given value and returns the first corresponding key if successful
    • array_shift - Shift an element off the beginning of array
    • array_slice - Extract a slice of the array
    • array_splice - Remove a portion of the array and replace it with something else
    • array_sum - Calculate the sum of values in an array
    • array_udiff - Computes the difference of arrays by using a callback function for data comparison
    • array_udiff_assoc - Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_uintersect - Computes the intersection of arrays, compares data by a callback function
    • array_uintersect_assoc - Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_unique - Removes duplicate values from an array
    • array_unshift - Prepend one or more elements to the beginning of an array
    • array_values - Return all the values of an array
    • array_walk - Apply a user supplied function to every member of an array
    • array_walk_recursive - Apply a user function recursively to every member of an array
    • arsort - Sort an array in descending order and maintain index association
    • asin - Arc sine
    • asinh - Inverse hyperbolic sine
    • asort - Sort an array in ascending order and maintain index association
    • assert - Checks an assertion
    • assert_options - Set/get the various assert flags
    • atan - Arc tangent
    • atan2 - Arc tangent of two variables
    • atanh - Inverse hyperbolic tangent
    • Attribute::__construct - Construct a new Attribute instance
  • b
    • BackedEnum::from - Maps a scalar to an enum instance
    • BackedEnum::tryFrom - Maps a scalar to an enum instance or null
    • base64_decode - Decodes data encoded with MIME base64
    • base64_encode - Encodes data with MIME base64
    • basename - Returns trailing name component of path
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • base_convert - Convert a number between arbitrary bases
    • bcadd - Add two arbitrary precision numbers
    • bccomp - Compare two arbitrary precision numbers
    • bcdiv - Divide two arbitrary precision numbers
    • bcmod - Get modulus of an arbitrary precision number
    • bcmul - Multiply two arbitrary precision numbers
    • bcpow - Raise an arbitrary precision number to another
    • bcpowmod - Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale - Set or get default scale parameter for all bc math functions
    • bcsqrt - Get the square root of an arbitrary precision number
    • bcsub - Subtract one arbitrary precision number from another
    • bin2hex - Convert binary data into hexadecimal representation
    • bindec - Binary to decimal
    • bindtextdomain - Sets or gets the path for a domain
    • bind_textdomain_codeset - Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
    • boolval - Get the boolean value of a variable
    • bzclose - Close a bzip2 file
    • bzcompress - Compress a string into bzip2 encoded data
    • bzdecompress - Decompresses bzip2 encoded data
    • bzerrno - Returns a bzip2 error number
    • bzerror - Returns the bzip2 error number and error string in an array
    • bzerrstr - Returns a bzip2 error string
    • bzflush - Do nothing
    • bzopen - Opens a bzip2 compressed file
    • bzread - Binary safe bzip2 file read
    • bzwrite - Binary safe bzip2 file write
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - Retrieve the contents of the cache
    • CachingIterator::getFlags - Get flags used
    • CachingIterator::hasNext - Check whether the inner iterator has a valid next element
    • CachingIterator::key - Return the key for the current element
    • CachingIterator::next - Move the iterator forward
    • CachingIterator::offsetExists - The offsetExists purpose
    • CachingIterator::offsetGet - The offsetGet purpose
    • CachingIterator::offsetSet - The offsetSet purpose
    • CachingIterator::offsetUnset - The offsetUnset purpose
    • CachingIterator::rewind - Rewind the iterator
    • CachingIterator::setFlags - The setFlags purpose
    • CachingIterator::valid - Check whether the current element is valid
    • CachingIterator::__construct - Construct a new CachingIterator object for the iterator
    • CachingIterator::__toString - Return the string representation of the current element
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - Call the callback given by the first parameter
    • call_user_func_array - Call a callback with an array of parameters
    • cal_days_in_month - Return the number of days in a month for a given year and calendar
    • cal_from_jd - Converts from Julian Day Count to a supported calendar
    • cal_info - Returns information about a particular calendar
    • cal_to_jd - Converts from a supported calendar to Julian Day Count
    • ceil - Round fractions up
    • chdir - Change directory
    • checkdate - Validate a Gregorian date
    • checkdnsrr - Check DNS records corresponding to a given Internet host name or IP address
    • chgrp - Changes file group
    • chmod - Changes file mode
    • chop - Alias of rtrim
    • chown - Changes file owner
    • chr - Generate a single-byte string from a number
    • chroot - Change the root directory
    • chunk_split - Split a string into smaller chunks
    • class_alias - Creates an alias for a class
    • class_exists - Checks if the class has been defined
    • 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 - Clears file status cache
    • Client::getClient - Get client session
    • Client::__construct - Client constructor
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - Close directory handle
    • closelog - Close connection to system logger
    • Closure::bind - Duplicates a closure with a specific bound object and class scope
    • Closure::bindTo - Duplicates the closure with a new bound object and class scope
    • Closure::call - Binds and calls the closure
    • Closure::fromCallable - Converts a callable into a closure
    • Closure::__construct - Constructor that disallows instantiation
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • Collator::create - Create a collator
    • Collator::getAttribute - Get collation attribute value
    • Collator::getErrorCode - Get collator's last error code
    • Collator::getErrorMessage - Get text for collator's last error code
    • Collator::getLocale - Get the locale name of the collator
    • Collator::getSortKey - Get sorting key for a string
    • Collator::getStrength - Get current collation strength
    • Collator::setAttribute - Set collation attribute
    • Collator::setStrength - Set collation strength
    • Collator::sort - Sort array using specified collator
    • Collator::sortWithSortKeys - Sort array using specified collator and sort keys
    • Collator::__construct - Create a collator
    • Collectable::isGarbage - Determine whether an object has been marked as garbage
    • Collection::add - Add collection document
    • Collection::addOrReplaceOne - Add or replace collection document
    • Collection::count - Get document count
    • Collection::createIndex - Create collection index
    • Collection::dropIndex - Drop collection index
    • Collection::existsInDatabase - Check if collection exists in database
    • Collection::find - Search for document
    • Collection::getName - Get collection name
    • Collection::getOne - Get one document
    • Collection::getSchema - Get schema object
    • Collection::getSession - Get session object
    • Collection::modify - Modify collection documents
    • Collection::remove - Remove collection documents
    • Collection::removeOne - Remove one collection document
    • Collection::replaceOne - Replace one collection document
    • Collection::__construct - Collection constructor
    • CollectionAdd::execute - Execute the statement
    • CollectionAdd::__construct - CollectionAdd constructor
    • CollectionFind::bind - Bind value to query placeholder
    • CollectionFind::execute - Execute the statement
    • CollectionFind::fields - Set document field filter
    • CollectionFind::groupBy - Set grouping criteria
    • CollectionFind::having - Set condition for aggregate functions
    • CollectionFind::limit - Limit number of returned documents
    • CollectionFind::lockExclusive - Execute operation with EXCLUSIVE LOCK
    • CollectionFind::lockShared - Execute operation with SHARED LOCK
    • CollectionFind::offset - Skip given number of elements to be returned
    • CollectionFind::sort - Set the sorting criteria
    • CollectionFind::__construct - CollectionFind constructor
    • CollectionModify::arrayAppend - Append element to an array field
    • CollectionModify::arrayInsert - Insert element into an array field
    • CollectionModify::bind - Bind value to query placeholder
    • CollectionModify::execute - Execute modify operation
    • CollectionModify::limit - Limit number of modified documents
    • CollectionModify::patch - Patch document
    • CollectionModify::replace - Replace document field
    • CollectionModify::set - Set document attribute
    • CollectionModify::skip - Skip elements
    • CollectionModify::sort - Set the sorting criteria
    • CollectionModify::unset - Unset the value of document fields
    • CollectionModify::__construct - CollectionModify constructor
    • CollectionRemove::bind - Bind value to placeholder
    • CollectionRemove::execute - Execute remove operation
    • CollectionRemove::limit - Limit number of documents to remove
    • CollectionRemove::sort - Set the sorting criteria
    • CollectionRemove::__construct - CollectionRemove constructor
    • ColumnResult::getCharacterSetName - Get character set
    • ColumnResult::getCollationName - Get collation name
    • ColumnResult::getColumnLabel - Get column label
    • ColumnResult::getColumnName - Get column name
    • ColumnResult::getFractionalDigits - Get fractional digit length
    • ColumnResult::getLength - Get column field length
    • ColumnResult::getSchemaName - Get schema name
    • ColumnResult::getTableLabel - Get table label
    • ColumnResult::getTableName - Get table name
    • ColumnResult::getType - Get column type
    • ColumnResult::isNumberSigned - Check if signed type
    • ColumnResult::isPadded - Check if padded
    • ColumnResult::__construct - ColumnResult constructor
    • com::__construct - com class constructor
    • CommonMark\CQL::__construct - CQL Construction
    • CommonMark\CQL::__invoke - CQL Execution
    • CommonMark\Interfaces\IVisitable::accept - Visitation
    • CommonMark\Interfaces\IVisitor::enter - Visitation
    • CommonMark\Interfaces\IVisitor::leave - Visitation
    • CommonMark\Node::accept - Visitation
    • CommonMark\Node::appendChild - AST Manipulation
    • CommonMark\Node::insertAfter - AST Manipulation
    • CommonMark\Node::insertBefore - AST Manipulation
    • CommonMark\Node::prependChild - AST Manipulation
    • CommonMark\Node::replace - AST Manipulation
    • CommonMark\Node::unlink - AST Manipulation
    • CommonMark\Node\BulletList::__construct - BulletList Construction
    • CommonMark\Node\CodeBlock::__construct - CodeBlock Construction
    • CommonMark\Node\Heading::__construct - Heading Construction
    • CommonMark\Node\Image::__construct - Image Construction
    • CommonMark\Node\Link::__construct - Link Construction
    • CommonMark\Node\OrderedList::__construct - OrderedList Construction
    • CommonMark\Node\Text::__construct - Text Construction
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Parsing
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - Create array containing variables and their values
    • COMPersistHelper::GetCurFileName - Get current filename
    • COMPersistHelper::GetMaxStreamSize - Get maximum stream size
    • COMPersistHelper::InitNew - Initialize object to default state
    • COMPersistHelper::LoadFromFile - Load object from file
    • COMPersistHelper::LoadFromStream - Load object from stream
    • COMPersistHelper::SaveToFile - Save object to file
    • COMPersistHelper::SaveToStream - Save object to stream
    • COMPersistHelper::__construct - Construct a COMPersistHelper object
    • Componere\Abstract\Definition::addInterface - Add Interface
    • Componere\Abstract\Definition::addMethod - Add Method
    • Componere\Abstract\Definition::addTrait - Add Trait
    • Componere\Abstract\Definition::getReflector - Reflection
    • Componere\cast - Casting
    • Componere\cast_by_ref - Casting
    • Componere\Definition::addConstant - Add Constant
    • Componere\Definition::addProperty - Add Property
    • Componere\Definition::getClosure - Get Closure
    • Componere\Definition::getClosures - Get Closures
    • Componere\Definition::isRegistered - State Detection
    • Componere\Definition::register - Registration
    • Componere\Definition::__construct - Definition Construction
    • Componere\Method::getReflector - Reflection
    • Componere\Method::setPrivate - Accessibility Modification
    • Componere\Method::setProtected - Accessibility Modification
    • Componere\Method::setStatic - Accessibility Modification
    • Componere\Method::__construct - Method Construction
    • Componere\Patch::apply - Application
    • Componere\Patch::derive - Patch Derivation
    • Componere\Patch::getClosure - Get Closure
    • Componere\Patch::getClosures - Get Closures
    • Componere\Patch::isApplied - State Detection
    • Componere\Patch::revert - Reversal
    • Componere\Patch::__construct - Patch Construction
    • Componere\Value::hasDefault - Value Interaction
    • Componere\Value::isPrivate - Accessibility Detection
    • Componere\Value::isProtected - Accessibility Detection
    • Componere\Value::isStatic - Accessibility Detection
    • Componere\Value::setPrivate - Accessibility Modification
    • Componere\Value::setProtected - Accessibility Modification
    • Componere\Value::setStatic - Accessibility Modification
    • Componere\Value::__construct - Value Construction
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_load_typelib - Loads a Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • connection_aborted - Check whether client disconnected
    • connection_status - Returns connection status bitfield
    • constant - Returns the value of a constant
    • Context parameters - Context parameter listing
    • convert_cyr_string - Convert from one Cyrillic character set to another
    • convert_uudecode - Decode a uuencoded string
    • convert_uuencode - Uuencode a string
    • copy - Copies file
    • cos - Cosine
    • cosh - Hyperbolic cosine
    • count - Counts all elements in an array or in a Countable object
    • Countable::count - Count elements of an object
    • count_chars - Return information about characters used in a string
    • crc32 - Calculates the crc32 polynomial of a string
    • create_function - Create a function dynamically by evaluating a string of code
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • crypt - One-way string hashing
    • ctype_alnum - Check for alphanumeric character(s)
    • ctype_alpha - Check for alphabetic character(s)
    • ctype_cntrl - Check for control character(s)
    • ctype_digit - Check for numeric character(s)
    • ctype_graph - Check for any printable character(s) except space
    • ctype_lower - Check for lowercase character(s)
    • ctype_print - Check for printable character(s)
    • ctype_punct - Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space - Check for whitespace character(s)
    • ctype_upper - Check for uppercase character(s)
    • ctype_xdigit - Check for character(s) representing a hexadecimal digit
    • 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 - Get file name
    • CURLFile::getMimeType - Get MIME type
    • CURLFile::getPostFilename - Get file name for POST
    • CURLFile::setMimeType - Set MIME type
    • CURLFile::setPostFilename - Set file name for POST
    • CURLFile::__construct - Create a CURLFile object
    • CURLStringFile::__construct - Create a CURLStringFile object
    • curl_close - Close a cURL session
    • curl_copy_handle - Copy a cURL handle along with all of its preferences
    • curl_errno - Return the last error number
    • curl_error - Return a string containing the last error for the current session
    • curl_escape - URL encodes the given string
    • curl_exec - Perform a cURL session
    • curl_getinfo - Get information regarding a specific transfer
    • curl_init - Initialize a cURL session
    • curl_multi_add_handle - Add a normal cURL handle to a cURL multi handle
    • curl_multi_close - Close a set of cURL handles
    • curl_multi_errno - Return the last multi curl error number
    • curl_multi_exec - Run the sub-connections of the current cURL handle
    • curl_multi_getcontent - Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read - Get information about the current transfers
    • curl_multi_init - Returns a new cURL multi handle
    • curl_multi_remove_handle - Remove a multi handle from a set of cURL handles
    • curl_multi_select - Wait for activity on any curl_multi connection
    • curl_multi_setopt - Set a cURL multi option
    • curl_multi_strerror - Return string describing error code
    • curl_pause - Pause and unpause a connection
    • curl_reset - Reset all options of a libcurl session handle
    • curl_setopt - Set an option for a cURL transfer
    • curl_setopt_array - Set multiple options for a cURL transfer
    • curl_share_close - Close a cURL share handle
    • curl_share_errno - Return the last share curl error number
    • curl_share_init - Initialize a cURL share handle
    • curl_share_setopt - Set an option for a cURL share handle
    • curl_share_strerror - Return string describing the given error code
    • curl_strerror - Return string describing the given error code
    • curl_unescape - Decodes the given URL encoded string
    • curl_upkeep - Performs any connection upkeep checks
    • curl_version - Gets cURL version information
    • current - Return the current element in an array
  • d
    • data:// - Data (RFC 2397)
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • date - Format a Unix timestamp
    • DateInterval::createFromDateString - Sets up a DateInterval from the relative parts of the string
    • DateInterval::format - Formats the interval
    • DateInterval::__construct - Creates a new DateInterval object
    • DatePeriod::createFromISO8601String - Creates a new DatePeriod object from an ISO8601 string
    • DatePeriod::getDateInterval - Gets the interval
    • DatePeriod::getEndDate - Gets the end date
    • DatePeriod::getRecurrences - Gets the number of recurrences
    • DatePeriod::getStartDate - Gets the start date
    • DatePeriod::__construct - Creates a new DatePeriod object
    • DateTime::add - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
    • DateTime::createFromFormat - Parses a time string according to a specified format
    • DateTime::createFromImmutable - Returns new DateTime instance encapsulating the given DateTimeImmutable object
    • DateTime::createFromInterface - Returns new DateTime object encapsulating the given DateTimeInterface object
    • DateTime::getLastErrors - Alias of DateTimeImmutable::getLastErrors
    • DateTime::modify - Alters the timestamp
    • DateTime::setDate - Sets the date
    • DateTime::setISODate - Sets the ISO date
    • DateTime::setTime - Sets the time
    • DateTime::setTimestamp - Sets the date and time based on an Unix timestamp
    • DateTime::setTimezone - Sets the time zone for the DateTime object
    • DateTime::sub - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
    • DateTime::__construct - Returns new DateTime object
    • DateTime::__set_state - The __set_state handler
    • DateTime::__wakeup - The __wakeup handler
    • DateTimeImmutable::add - Returns a new object, with added amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::createFromFormat - Parses a time string according to a specified format
    • DateTimeImmutable::createFromInterface - Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
    • DateTimeImmutable::createFromMutable - Returns new DateTimeImmutable instance encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors - Returns the warnings and errors
    • DateTimeImmutable::modify - Creates a new object with modified timestamp
    • DateTimeImmutable::setDate - Sets the date
    • DateTimeImmutable::setISODate - Sets the ISO date
    • DateTimeImmutable::setTime - Sets the time
    • DateTimeImmutable::setTimestamp - Sets the date and time based on a Unix timestamp
    • DateTimeImmutable::setTimezone - Sets the time zone
    • DateTimeImmutable::sub - Subtracts an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct - Returns new DateTimeImmutable object
    • DateTimeImmutable::__set_state - The __set_state handler
    • DateTimeInterface::diff - Returns the difference between two DateTime objects
    • DateTimeInterface::format - Returns date formatted according to given format
    • DateTimeInterface::getOffset - Returns the timezone offset
    • DateTimeInterface::getTimestamp - Gets the Unix timestamp
    • DateTimeInterface::getTimezone - Return time zone relative to given DateTime
    • DateTimeZone::getLocation - Returns location information for a timezone
    • DateTimeZone::getName - Returns the name of the timezone
    • DateTimeZone::getOffset - Returns the timezone offset from GMT
    • DateTimeZone::getTransitions - Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations - Returns associative array containing dst, offset and the timezone name
    • DateTimeZone::listIdentifiers - Returns a numerically indexed array containing all defined timezone identifiers
    • DateTimeZone::__construct - Creates new DateTimeZone object
    • date_add - Alias of DateTime::add
    • date_create - create a new DateTime object
    • date_create_from_format - Alias of DateTime::createFromFormat
    • date_create_immutable - create a new DateTimeImmutable object
    • date_create_immutable_from_format - Alias of DateTimeImmutable::createFromFormat
    • date_date_set - Alias of DateTime::setDate
    • date_default_timezone_get - Gets the default timezone used by all date/time functions in a script
    • date_default_timezone_set - Sets the default timezone used by all date/time functions in a script
    • date_diff - Alias of DateTime::diff
    • date_format - Alias of DateTime::format
    • date_get_last_errors - Alias of DateTimeImmutable::getLastErrors
    • date_interval_create_from_date_string - Alias of DateInterval::createFromDateString
    • date_interval_format - Alias of DateInterval::format
    • date_isodate_set - Alias of DateTime::setISODate
    • date_modify - Alias of DateTime::modify
    • date_offset_get - Alias of DateTime::getOffset
    • date_parse - Returns associative array with detailed info about given date/time
    • date_parse_from_format - Get info about given date formatted according to the specified format
    • date_sub - Alias of DateTime::sub
    • date_sunrise - Returns time of sunrise for a given day and location
    • date_sunset - Returns time of sunset for a given day and location
    • date_sun_info - Returns an array with information about sunset/sunrise and twilight begin/end
    • date_timestamp_get - Alias of DateTime::getTimestamp
    • date_timestamp_set - Alias of DateTime::setTimestamp
    • date_timezone_get - Alias of DateTime::getTimezone
    • date_timezone_set - Alias of DateTime::setTimezone
    • date_time_set - Alias of 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 - Adds a record to a database
    • dbase_close - Closes a database
    • dbase_create - Creates a database
    • dbase_delete_record - Deletes a record from a database
    • dbase_get_header_info - Gets the header info of a database
    • dbase_get_record - Gets a record from a database as an indexed array
    • dbase_get_record_with_names - Gets a record from a database as an associative array
    • dbase_numfields - Gets the number of fields of a database
    • dbase_numrecords - Gets the number of records in a database
    • dbase_open - Opens a database
    • dbase_pack - Packs a database
    • dbase_replace_record - Replaces a record in a database
    • dba_close - Close a DBA database
    • dba_delete - Delete DBA entry specified by key
    • dba_exists - Check whether key exists
    • dba_fetch - Fetch data specified by key
    • dba_firstkey - Fetch first key
    • dba_handlers - List all the handlers available
    • dba_insert - Insert entry
    • dba_key_split - Splits a key in string representation into array representation
    • dba_list - List all open database files
    • dba_nextkey - Fetch next key
    • dba_open - Open database
    • dba_optimize - Optimize database
    • dba_popen - Open database persistently
    • dba_replace - Replace or insert entry
    • dba_sync - Synchronize database
    • dcgettext - Overrides the domain for a single lookup
    • dcngettext - Plural version of dcgettext
    • debug_backtrace - Generates a backtrace
    • debug_print_backtrace - Prints a backtrace
    • debug_zval_dump - Dumps a string representation of an internal zval structure to output
    • decbin - Decimal to binary
    • dechex - Decimal to hexadecimal
    • decoct - Decimal to octal
    • define - Defines a named constant
    • defined - Checks whether a given named constant exists
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Converts the number in degrees to the radian equivalent
    • delete - See unlink or unset
    • dgettext - Override the current domain
    • die - Equivalent to exit
    • dio_close - Closes the file descriptor given by fd
    • dio_fcntl - Performs a c library fcntl on fd
    • dio_open - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow
    • dio_read - Reads bytes from a file descriptor
    • dio_seek - Seeks to pos on fd from whence
    • dio_stat - Gets stat information about the file descriptor fd
    • dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
    • dio_truncate - Truncates file descriptor fd to offset bytes
    • dio_write - Writes data to fd with optional truncation at length
    • dir - Return an instance of the Directory class
    • Directory::close - Close directory handle
    • Directory::read - Read entry from directory handle
    • Directory::rewind - Rewind directory handle
    • 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 - Returns a parent directory's path
    • diskfreespace - Alias of disk_free_space
    • disk_free_space - Returns available space on filesystem or disk partition
    • disk_total_space - Returns the total size of a filesystem or disk partition
    • dl - Loads a PHP extension at runtime
    • dngettext - Plural version of dgettext
    • dns_check_record - Alias of checkdnsrr
    • dns_get_mx - Alias of getmxrr
    • dns_get_record - Fetch DNS Resource Records associated with a hostname
    • DocResult::fetchAll - Get all rows
    • DocResult::fetchOne - Get one row
    • DocResult::getWarnings - Get warnings from last operation
    • DocResult::getWarningsCount - Get warning count from last operation
    • DocResult::__construct - DocResult constructor
    • DOMAttr::isId - Checks if attribute is a defined ID
    • DOMAttr::__construct - Creates a new DOMAttr object
    • DOMCdataSection::__construct - Constructs a new DOMCdataSection object
    • DOMCharacterData::after - Adds nodes after the character data
    • DOMCharacterData::appendData - Append the string to the end of the character data of the node
    • DOMCharacterData::before - Adds nodes before the node
    • DOMCharacterData::deleteData - Remove a range of characters from the node
    • DOMCharacterData::insertData - Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::remove - Removes the character data
    • DOMCharacterData::replaceData - Replace a substring within the DOMCharacterData node
    • DOMCharacterData::replaceWith - Replaces the character data with new nodes
    • DOMCharacterData::substringData - Extracts a range of data from the node
    • DOMChildNode::after - Adds nodes after the node
    • DOMChildNode::before - Adds nodes before the node
    • DOMChildNode::remove - Removes the node
    • DOMChildNode::replaceWith - Replaces the node with new nodes
    • DOMComment::__construct - Creates a new DOMComment object
    • DOMDocument::adoptNode - Transfer a node from another document
    • DOMDocument::append - Appends nodes after the last child node
    • DOMDocument::createAttribute - Create new attribute
    • DOMDocument::createAttributeNS - Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection - Create new cdata node
    • DOMDocument::createComment - Create new comment node
    • DOMDocument::createDocumentFragment - Create new document fragment
    • DOMDocument::createElement - Create new element node
    • DOMDocument::createElementNS - Create new element node with an associated namespace
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Creates new PI node
    • DOMDocument::createTextNode - Create new text node
    • DOMDocument::getElementById - Searches for an element with a certain id
    • DOMDocument::getElementsByTagName - Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS - Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode - Import node into current document
    • DOMDocument::load - Load XML from a file
    • DOMDocument::loadHTML - Load HTML from a string
    • DOMDocument::loadHTMLFile - Load HTML from a file
    • DOMDocument::loadXML - Load XML from a string
    • DOMDocument::normalizeDocument - Normalizes the document
    • DOMDocument::prepend - Prepends nodes before the first child node
    • DOMDocument::registerNodeClass - Register extended class used to create base node type
    • DOMDocument::relaxNGValidate - Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource - Performs relaxNG validation on the document
    • DOMDocument::replaceChildren - Replace children in document
    • DOMDocument::save - Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML - Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile - Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML - Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate - Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource - Validates a document based on a schema
    • DOMDocument::validate - Validates the document based on its DTD
    • DOMDocument::xinclude - Substitutes XIncludes in a DOMDocument Object
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::append - Appends nodes after the last child node
    • DOMDocumentFragment::appendXML - Append raw XML data
    • DOMDocumentFragment::prepend - Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren - Replace children in fragment
    • DOMDocumentFragment::__construct - Constructs a DOMDocumentFragment object
    • DOMElement::after - Adds nodes after the element
    • DOMElement::append - Appends nodes after the last child node
    • DOMElement::before - Adds nodes before the element
    • DOMElement::getAttribute - Returns value of attribute
    • DOMElement::getAttributeNames - Get attribute names
    • DOMElement::getAttributeNode - Returns attribute node
    • DOMElement::getAttributeNodeNS - Returns attribute node
    • DOMElement::getAttributeNS - Returns value of attribute
    • DOMElement::getElementsByTagName - Gets elements by tagname
    • DOMElement::getElementsByTagNameNS - Get elements by namespaceURI and localName
    • DOMElement::hasAttribute - Checks to see if attribute exists
    • DOMElement::hasAttributeNS - Checks to see if attribute exists
    • DOMElement::insertAdjacentElement - Insert adjacent element
    • DOMElement::insertAdjacentText - Insert adjacent text
    • DOMElement::prepend - Prepends nodes before the first child node
    • DOMElement::remove - Removes the element
    • DOMElement::removeAttribute - Removes attribute
    • DOMElement::removeAttributeNode - Removes attribute
    • DOMElement::removeAttributeNS - Removes attribute
    • DOMElement::replaceChildren - Replace children in element
    • DOMElement::replaceWith - Replaces the element with new nodes
    • DOMElement::setAttribute - Adds new or modifies existing attribute
    • DOMElement::setAttributeNode - Adds new attribute node to element
    • DOMElement::setAttributeNodeNS - Adds new attribute node to element
    • DOMElement::setAttributeNS - Adds new attribute
    • DOMElement::setIdAttribute - Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode - Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS - Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::toggleAttribute - Toggle attribute
    • DOMElement::__construct - Creates a new DOMElement object
    • DOMEntityReference::__construct - Creates a new DOMEntityReference object
    • DOMImplementation::createDocument - Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType - Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature - Test if the DOM implementation implements a specific feature
    • DOMImplementation::__construct - Creates a new DOMImplementation object
    • DOMNamedNodeMap::count - Get number of nodes in the map
    • DOMNamedNodeMap::getIterator - Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem - Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS - Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item - Retrieves a node specified by index
    • DOMNode::appendChild - 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 - Gets a DOMElement object from a SimpleXMLElement object
    • dotnet::__construct - dotnet class constructor
    • doubleval - Alias of 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 - Return the current key and value pair from an array and advance the array cursor
    • easter_date - Get Unix timestamp for midnight on Easter of a given year
    • easter_days - Get number of days after March 21 on which Easter falls for a given year
    • echo - Output one or more strings
    • eio_busy - Artificially increase load. Could be useful in tests, benchmarking
    • eio_cancel - Cancels a request
    • eio_chmod - Change file/directory permissions
    • eio_chown - Change file/directory permissions
    • eio_close - Close file
    • eio_custom - Execute custom request like any other eio_* call
    • eio_dup2 - Duplicate a file descriptor
    • eio_event_loop - Polls libeio until all requests proceeded
    • eio_fallocate - Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod - Change file permissions
    • eio_fchown - Change file ownership
    • eio_fdatasync - Synchronize a file's in-core state with storage device
    • eio_fstat - Get file status
    • eio_fstatvfs - Get file system statistics
    • eio_fsync - Synchronize a file's in-core state with storage device
    • eio_ftruncate - Truncate a file
    • eio_futime - Change file last access and modification times
    • eio_get_event_stream - Get stream representing a variable used in internal communications with libeio
    • eio_get_last_error - Returns string describing the last error associated with a request resource
    • eio_grp - Creates a request group
    • eio_grp_add - Adds a request to the request group
    • eio_grp_cancel - Cancels a request group
    • eio_grp_limit - Set group limit
    • eio_init - (Re-)initialize Eio
    • eio_link - Create a hardlink for file
    • eio_lstat - Get file status
    • eio_mkdir - Create directory
    • eio_mknod - Create a special or ordinary file
    • eio_nop - Does nothing, except go through the whole request cycle
    • eio_npending - Returns number of finished, but unhandled requests
    • eio_nready - Returns number of not-yet handled requests
    • eio_nreqs - Returns number of requests to be processed
    • eio_nthreads - Returns number of threads currently in use
    • eio_open - Opens a file
    • eio_poll - Can be to be called whenever there are pending requests that need finishing
    • eio_read - Read from a file descriptor at given offset
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Reads through a whole directory
    • eio_readlink - Read value of a symbolic link
    • eio_realpath - Get the canonicalized absolute pathname
    • eio_rename - Change the name or location of a file
    • eio_rmdir - Remove a directory
    • eio_seek - Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • eio_sendfile - Transfer data between file descriptors
    • eio_set_max_idle - Set maximum number of idle threads
    • eio_set_max_parallel - Set maximum parallel threads
    • eio_set_max_poll_reqs - Set maximum number of requests processed in a poll
    • eio_set_max_poll_time - Set maximum poll time
    • eio_set_min_parallel - Set minimum parallel thread number
    • eio_stat - Get file status
    • eio_statvfs - Get file system statistics
    • eio_symlink - Create a symbolic link
    • eio_sync - Commit buffer cache to disk
    • eio_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • eio_truncate - Truncate a file
    • eio_unlink - Delete a name and possibly the file it refers to
    • eio_utime - Change file last access and modification times
    • eio_write - Write to file
    • empty - Determine whether a variable is empty
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - The valid() method
    • enchant_broker_describe - Enumerates the Enchant providers
    • enchant_broker_dict_exists - Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free - Free the broker resource and its dictionaries
    • enchant_broker_free_dict - Free a dictionary resource
    • enchant_broker_get_dict_path - Get the directory path for a given backend
    • enchant_broker_get_error - Returns the last error of the broker
    • enchant_broker_init - Create a new broker object capable of requesting
    • enchant_broker_list_dicts - Returns a list of available dictionaries
    • enchant_broker_request_dict - Create a new dictionary using a tag
    • enchant_broker_request_pwl_dict - Creates a dictionary using a PWL file
    • enchant_broker_set_dict_path - Set the directory path for a given backend
    • enchant_broker_set_ordering - Declares a preference of dictionaries to use for the language
    • enchant_dict_add - Add a word to personal word list
    • enchant_dict_add_to_personal - Alias of 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 of 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 - Set the internal pointer of an array to its last element
    • enum_exists - Checks if the enum has been defined
    • Error::getCode - Gets the error code
    • Error::getFile - Gets the file in which the error occurred
    • Error::getLine - Gets the line in which the error occurred
    • Error::getMessage - Gets the error message
    • Error::getPrevious - Returns previous Throwable
    • Error::getTrace - Gets the stack trace
    • Error::getTraceAsString - Gets the stack trace as a string
    • Error::__clone - Clone the error
    • Error::__construct - Construct the error object
    • Error::__toString - String representation of the error
    • ErrorException::getSeverity - Gets the exception severity
    • ErrorException::__construct - Constructs the exception
    • error_clear_last - Clear the most recent error
    • error_get_last - Get the last occurred error
    • error_log - Send an error message to the defined error handling routines
    • error_reporting - Sets which PHP errors are reported
    • escapeshellarg - Escape a string to be used as a shell argument
    • escapeshellcmd - Escape shell metacharacters
    • Ev::backend - Returns an integer describing the backend used by libev
    • Ev::depth - Returns recursion depth
    • Ev::embeddableBackends - Returns the set of backends that are embeddable in other event loops
    • Ev::feedSignal - Feed a signal event info Ev
    • Ev::feedSignalEvent - Feed signal event into the default loop
    • Ev::iteration - Return the number of times the default event loop has polled for new events
    • Ev::now - Returns the time when the last iteration of the default event loop has started
    • Ev::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
    • Ev::recommendedBackends - Returns a bit mask of recommended backends for current platform
    • Ev::resume - Resume previously suspended default event loop
    • Ev::run - Begin checking for events and calling callbacks for the default loop
    • Ev::sleep - Block the process for the given number of seconds
    • Ev::stop - Stops the default event loop
    • Ev::supportedBackends - Returns the set of backends supported by current libev configuration
    • Ev::suspend - Suspend the default event loop
    • Ev::time - Returns the current time in fractional seconds since the epoch
    • Ev::verify - Performs internal consistency checks(for debugging)
    • eval - Evaluate a string as PHP code
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher object
    • EvEmbed::createStopped - Create stopped EvEmbed watcher object
    • EvEmbed::set - Configures the watcher
    • EvEmbed::sweep - Make a single, non-blocking sweep over the embedded loop
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Alias of Event::add
    • Event::addTimer - Alias of Event::add
    • Event::del - Makes event non-pending
    • Event::delSignal - Alias of Event::del
    • Event::delTimer - Alias of 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 - Description
    • EventBuffer::expand - Reserves space in buffer
    • EventBuffer::freeze - Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock - Acquires a lock on buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Constructs EventBuffer object
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::setFlags - Sets one or more flags to configure the eventual EventBase will be initialized
    • EventConfig::setMaxDispatchInterval - Prevents priority inversion
    • EventConfig::__construct - Constructs EventConfig object
    • EventDnsBase::addNameserverIp - Adds a nameserver to the DNS base
    • EventDnsBase::addSearch - Adds a domain to the list of search domains
    • EventDnsBase::clearSearch - Removes all current search suffixes
    • EventDnsBase::countNameservers - Gets the number of configured nameservers
    • EventDnsBase::loadHosts - Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf - Scans the resolv.conf-formatted file
    • EventDnsBase::setOption - Set the value of a configuration option
    • EventDnsBase::setSearchNdots - Set the 'ndots' parameter for searches
    • EventDnsBase::__construct - Constructs EventDnsBase object
    • EventHttp::accept - Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias - Adds a server alias to the HTTP server object
    • EventHttp::bind - Binds an HTTP server on the specified address and port
    • EventHttp::removeServerAlias - Removes server alias
    • EventHttp::setAllowedMethods - Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback - Sets a callback for specified URI
    • EventHttp::setDefaultCallback - Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize - Sets maximum request body size
    • EventHttp::setMaxHeadersSize - Sets maximum HTTP header size
    • EventHttp::setTimeout - Sets the timeout for an HTTP request
    • EventHttp::__construct - Constructs EventHttp object(the HTTP server)
    • EventHttpConnection::getBase - Returns event base associated with the connection
    • EventHttpConnection::getPeer - Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest - Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback - Set callback for connection close
    • EventHttpConnection::setLocalAddress - Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort - Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize - Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize - Sets maximum header size
    • EventHttpConnection::setRetries - Sets the retry limit for the connection
    • EventHttpConnection::setTimeout - Sets the timeout for the connection
    • EventHttpConnection::__construct - Constructs EventHttpConnection object
    • EventHttpRequest::addHeader - Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel - Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders - Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection - Closes associated HTTP connection
    • EventHttpRequest::findHeader - Finds the value belonging a header
    • EventHttpRequest::free - Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent - Returns EventBufferEvent object
    • EventHttpRequest::getCommand - Returns the request command(method)
    • EventHttpRequest::getConnection - Returns EventHttpConnection object
    • EventHttpRequest::getHost - Returns the request host
    • EventHttpRequest::getInputBuffer - Returns the input buffer
    • EventHttpRequest::getInputHeaders - Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer - Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders - Returns associative array of the output headers
    • EventHttpRequest::getResponseCode - Returns the response code
    • EventHttpRequest::getUri - Returns the request URI
    • EventHttpRequest::removeHeader - Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError - Send an HTML error message to the client
    • EventHttpRequest::sendReply - Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk - Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd - Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart - Initiate a chunked reply
    • EventHttpRequest::__construct - Constructs EventHttpRequest object
    • EventListener::disable - Disables an event connect listener object
    • EventListener::enable - Enables an event connect listener object
    • EventListener::getBase - Returns event base associated with the event listener
    • EventListener::getSocketName - Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback - The setCallback purpose
    • EventListener::setErrorCallback - Set event listener's error callback
    • EventListener::__construct - Creates new connection listener associated with an event base
    • EventSslContext::__construct - Constructs an OpenSSL context for use with Event classes
    • EventUtil::getLastSocketErrno - Returns the most recent socket error number
    • EventUtil::getLastSocketError - Returns the most recent socket error
    • EventUtil::getSocketFd - Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName - Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption - Sets socket options
    • EventUtil::sslRandPoll - Generates entropy by means of OpenSSL's RAND_poll()
    • EventUtil::__construct - The abstract constructor
    • EvFork::createStopped - Creates a stopped instance of EvFork watcher class
    • EvFork::__construct - Constructs the EvFork watcher object
    • EvIdle::createStopped - Creates instance of a stopped EvIdle watcher object
    • EvIdle::__construct - Constructs the EvIdle watcher object
    • EvIo::createStopped - Create stopped EvIo watcher object
    • EvIo::set - Configures the watcher
    • EvIo::__construct - Constructs EvIo watcher object
    • EvLoop::backend - Returns an integer describing the backend used by libev
    • EvLoop::check - Creates EvCheck object associated with the current event loop instance
    • EvLoop::child - Creates EvChild object associated with the current event loop
    • EvLoop::defaultLoop - Returns or creates the default event loop
    • EvLoop::embed - Creates an instance of EvEmbed watcher associated with the current EvLoop object
    • EvLoop::fork - Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle - Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending - Invoke all pending watchers while resetting their pending state
    • EvLoop::io - Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork - Must be called after a fork
    • EvLoop::now - Returns the current "event loop time"
    • EvLoop::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
    • EvLoop::periodic - Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare - Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume - Resume previously suspended default event loop
    • EvLoop::run - Begin checking for events and calling callbacks for the loop
    • EvLoop::signal - Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat - Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop - Stops the event loop
    • EvLoop::suspend - Suspend the loop
    • EvLoop::timer - Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify - Performs internal consistency checks(for debugging)
    • EvLoop::__construct - Constructs the event loop object
    • EvPeriodic::again - Simply stops and restarts the periodic watcher again
    • EvPeriodic::at - Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::createStopped - Create a stopped EvPeriodic watcher
    • EvPeriodic::set - Configures the watcher
    • EvPeriodic::__construct - Constructs EvPeriodic watcher object
    • EvPrepare::createStopped - Creates a stopped instance of EvPrepare watcher
    • EvPrepare::__construct - Constructs EvPrepare watcher object
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configures the watcher
    • EvSignal::__construct - Constructs EvSignal watcher object
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Exception::getCode - Gets the Exception code
    • Exception::getFile - Gets the file in which the exception was created
    • Exception::getLine - Gets the line in which the exception was created
    • Exception::getMessage - Gets the Exception message
    • Exception::getPrevious - Returns previous Throwable
    • Exception::getTrace - Gets the stack trace
    • Exception::getTraceAsString - Gets the stack trace as a string
    • Exception::__clone - Clone the exception
    • Exception::__construct - Construct the exception
    • Exception::__toString - String representation of the exception
    • exec - Execute an external program
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • exif_imagetype - Determine the type of an image
    • exif_read_data - Reads the EXIF headers from an image file
    • exif_tagname - Get the header name for an index
    • exif_thumbnail - Retrieve the embedded thumbnail of an image
    • exit - Output a message and terminate the current script
    • exp - Calculates the exponent of 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 - Split a string by a string
    • expm1 - Returns exp($num) - 1, computed in a way that is accurate even when the value of number is close to zero
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • extension_loaded - Find out whether an extension is loaded
    • extract - Import variables into the current symbol table from an array
    • ezmlm_hash - Calculate the hash value needed by EZMLM
  • f
    • FANNConnection::getFromNeuron - Returns the postions of starting neuron
    • FANNConnection::getToNeuron - Returns the postions of terminating neuron
    • FANNConnection::getWeight - Returns the connection weight
    • FANNConnection::setWeight - Sets the connections weight
    • FANNConnection::__construct - The connection constructor
    • fann_cascadetrain_on_data - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
    • fann_clear_scaling_params - Clears scaling parameters
    • fann_copy - Creates a copy of a fann structure
    • fann_create_from_file - Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut_array - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse - Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_sparse_array - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_standard - Creates a standard fully connected backpropagation neural network
    • fann_create_standard_array - Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_train - Creates an empty training data struct
    • fann_create_train_from_callback - Creates the training data struct from a user supplied function
    • fann_descale_input - Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output - Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train - Descale input and output data based on previously calculated parameters
    • fann_destroy - Destroys the entire network and properly freeing all the associated memory
    • fann_destroy_train - Destructs the training data
    • fann_duplicate_train_data - Returns an exact copy of a fann train data
    • fann_get_activation_function - Returns the activation function
    • fann_get_activation_steepness - Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array - Get the number of bias in each layer in the network
    • fann_get_bit_fail - The number of fail bits
    • fann_get_bit_fail_limit - Returns the bit fail limit used during training
    • fann_get_cascade_activation_functions - Returns the cascade activation functions
    • fann_get_cascade_activation_functions_count - Returns the number of cascade activation functions
    • fann_get_cascade_activation_steepnesses - Returns the cascade activation steepnesses
    • fann_get_cascade_activation_steepnesses_count - The number of activation steepnesses
    • fann_get_cascade_candidate_change_fraction - Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit - Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs - Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs - Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs - Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs - Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs - Returns the minimum out epochs
    • fann_get_cascade_num_candidates - Returns the number of candidates used during training
    • fann_get_cascade_num_candidate_groups - Returns the number of candidate groups
    • fann_get_cascade_output_change_fraction - Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs - Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier - Returns the weight multiplier
    • fann_get_connection_array - Get connections in the network
    • fann_get_connection_rate - Get the connection rate used when the network was created
    • fann_get_errno - Returns the last error number
    • fann_get_errstr - Returns the last errstr
    • fann_get_layer_array - Get the number of neurons in each layer in the network
    • fann_get_learning_momentum - Returns the learning momentum
    • fann_get_learning_rate - Returns the learning rate
    • fann_get_MSE - Reads the mean square error from the network
    • fann_get_network_type - Get the type of neural network it was created as
    • fann_get_num_input - Get the number of input neurons
    • fann_get_num_layers - Get the number of layers in the neural network
    • fann_get_num_output - Get the number of output neurons
    • fann_get_quickprop_decay - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu - Returns the mu factor
    • fann_get_rprop_decrease_factor - Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max - Returns the maximum step-size
    • fann_get_rprop_delta_min - Returns the minimum step-size
    • fann_get_rprop_delta_zero - Returns the initial step-size
    • fann_get_rprop_increase_factor - Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift - Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor - Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature - Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift - Returns the sarprop weight decay shift
    • fann_get_total_connections - Get the total number of connections in the entire network
    • fann_get_total_neurons - Get the total number of neurons in the entire network
    • fann_get_training_algorithm - Returns the training algorithm
    • fann_get_train_error_function - Returns the error function used during training
    • fann_get_train_stop_function - Returns the stop function used during training
    • fann_init_weights - Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data - Returns the number of training patterns in the train data
    • fann_merge_train_data - Merges the train data
    • fann_num_input_train_data - Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data - Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error - Prints the error string
    • fann_randomize_weights - Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file - Reads a file that stores training data
    • fann_reset_errno - Resets the last error number
    • fann_reset_errstr - Resets the last error string
    • fann_reset_MSE - Resets the mean square error from the network
    • fann_run - Will run input through the neural network
    • fann_save - Saves the entire network to a configuration file
    • fann_save_train - Save the training structure to a file
    • fann_scale_input - Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_input_train_data - Scales the inputs in the training data to the specified range
    • fann_scale_output - Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data - Scales the outputs in the training data to the specified range
    • fann_scale_train - Scale input and output data based on previously calculated parameters
    • fann_scale_train_data - Scales the inputs and outputs in the training data to the specified range
    • fann_set_activation_function - Sets the activation function for supplied neuron and layer
    • fann_set_activation_function_hidden - Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer - Sets the activation function for all the neurons in the supplied layer
    • fann_set_activation_function_output - Sets the activation function for the output layer
    • fann_set_activation_steepness - Sets the activation steepness for supplied neuron and layer number
    • fann_set_activation_steepness_hidden - Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer - Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output - Sets the steepness of the activation steepness in the output layer
    • fann_set_bit_fail_limit - Set the bit fail limit used during training
    • fann_set_callback - Sets the callback function for use during training
    • fann_set_cascade_activation_functions - Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses - Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction - Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit - Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs - Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs - Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs - Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs - Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs - Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups - Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction - Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs - Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier - Sets the weight multiplier
    • fann_set_error_log - Sets where the errors are logged to
    • fann_set_input_scaling_params - Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum - Sets the learning momentum
    • fann_set_learning_rate - Sets the learning rate
    • fann_set_output_scaling_params - Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay - Sets the quickprop decay factor
    • fann_set_quickprop_mu - Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor - Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max - Sets the maximum step-size
    • fann_set_rprop_delta_min - Sets the minimum step-size
    • fann_set_rprop_delta_zero - Sets the initial step-size
    • fann_set_rprop_increase_factor - Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift - Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor - Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature - Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift - Sets the sarprop weight decay shift
    • fann_set_scaling_params - Calculate input and output scaling parameters for future use based on training data
    • fann_set_training_algorithm - Sets the training algorithm
    • fann_set_train_error_function - Sets the error function used during training
    • fann_set_train_stop_function - Sets the stop function used during training
    • fann_set_weight - Set a connection in the network
    • fann_set_weight_array - Set connections in the network
    • fann_shuffle_train_data - Shuffles training data, randomizing the order
    • fann_subset_train_data - Returns an copy of a subset of the train data
    • fann_test - Test with a set of inputs, and a set of desired outputs
    • fann_test_data - Test a set of training data and calculates the MSE for the training data
    • fann_train - Train one iteration with a set of inputs, and a set of desired outputs
    • fann_train_epoch - Train one epoch with a set of training data
    • fann_train_on_data - Trains on an entire dataset for a period of time
    • fann_train_on_file - Trains on an entire dataset, which is read from file, for a period of time
    • fastcgi_finish_request - Flushes all response data to the client
    • fbird_add_user - Alias of ibase_add_user
    • fbird_affected_rows - Alias of ibase_affected_rows
    • fbird_backup - Alias of ibase_backup
    • fbird_blob_add - Alias of ibase_blob_add
    • fbird_blob_cancel - Cancel creating blob
    • fbird_blob_close - Alias of ibase_blob_close
    • fbird_blob_create - Alias of ibase_blob_create
    • fbird_blob_echo - Alias of ibase_blob_echo
    • fbird_blob_get - Alias of ibase_blob_get
    • fbird_blob_import - Alias of ibase_blob_import
    • fbird_blob_info - Alias of ibase_blob_info
    • fbird_blob_open - Alias of ibase_blob_open
    • fbird_close - Alias of ibase_close
    • fbird_commit - Alias of ibase_commit
    • fbird_commit_ret - Alias of ibase_commit_ret
    • fbird_connect - Alias of ibase_connect
    • fbird_db_info - Alias of ibase_db_info
    • fbird_delete_user - Alias of ibase_delete_user
    • fbird_drop_db - Alias of ibase_drop_db
    • fbird_errcode - Alias of ibase_errcode
    • fbird_errmsg - Alias of ibase_errmsg
    • fbird_execute - Alias of ibase_execute
    • fbird_fetch_assoc - Alias of ibase_fetch_assoc
    • fbird_fetch_object - Alias of ibase_fetch_object
    • fbird_fetch_row - Alias of ibase_fetch_row
    • fbird_field_info - Alias of ibase_field_info
    • fbird_free_event_handler - Alias of ibase_free_event_handler
    • fbird_free_query - Alias of ibase_free_query
    • fbird_free_result - Alias of ibase_free_result
    • fbird_gen_id - Alias of ibase_gen_id
    • fbird_maintain_db - Alias of ibase_maintain_db
    • fbird_modify_user - Alias of ibase_modify_user
    • fbird_name_result - Alias of ibase_name_result
    • fbird_num_fields - Alias of ibase_num_fields
    • fbird_num_params - Alias of ibase_num_params
    • fbird_param_info - Alias of ibase_param_info
    • fbird_pconnect - Alias of ibase_pconnect
    • fbird_prepare - Alias of ibase_prepare
    • fbird_query - Alias of ibase_query
    • fbird_restore - Alias of ibase_restore
    • fbird_rollback - Alias of ibase_rollback
    • fbird_rollback_ret - Alias of ibase_rollback_ret
    • fbird_server_info - Alias of ibase_server_info
    • fbird_service_attach - Alias of ibase_service_attach
    • fbird_service_detach - Alias of ibase_service_detach
    • fbird_set_event_handler - Alias of ibase_set_event_handler
    • fbird_trans - Alias of ibase_trans
    • fbird_wait_event - Alias of ibase_wait_event
    • fclose - Closes an open file pointer
    • fdatasync - Synchronizes data (but not meta-data) to the file
    • fdf_add_doc_javascript - Adds javascript code to the FDF document
    • fdf_add_template - Adds a template into the FDF document
    • fdf_close - Close an FDF document
    • fdf_create - Create a new FDF document
    • fdf_enum_values - Call a user defined function for each document value
    • fdf_errno - Return error code for last fdf operation
    • fdf_error - Return error description for FDF error code
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Get the value of the /Encoding key
    • fdf_get_file - Get the value of the /F key
    • fdf_get_flags - Gets the flags of a field
    • fdf_get_opt - Gets a value from the opt array of a field
    • fdf_get_status - Get the value of the /STATUS key
    • fdf_get_value - Get the value of a field
    • fdf_get_version - Gets version number for FDF API or file
    • fdf_header - Sets FDF-specific output headers
    • fdf_next_field_name - Get the next field name
    • fdf_open - Open a FDF document
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Save a FDF document
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Set the appearance of a field
    • fdf_set_encoding - Sets FDF character encoding
    • fdf_set_file - Set PDF document to display FDF data in
    • fdf_set_flags - Sets a flag of a field
    • fdf_set_javascript_action - Sets an javascript action of a field
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Sets an option of a field
    • fdf_set_status - Set the value of the /STATUS key
    • fdf_set_submit_form_action - Sets a submit form action of a field
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Set the value of a field
    • fdf_set_version - Sets version number for a FDF file
    • fdiv - Divides two numbers, according to IEEE 754
    • feof - Tests for end-of-file on a file pointer
    • 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 - Flushes the output to a file
    • fgetc - Gets character from file pointer
    • fgetcsv - Gets line from file pointer and parse for CSV fields
    • fgets - Gets line from file pointer
    • fgetss - Gets line from file pointer and strip HTML tags
    • Fiber::getCurrent - Gets the currently executing Fiber instance
    • Fiber::getReturn - Gets the value returned by the Fiber
    • Fiber::isRunning - Determines if the fiber is running
    • Fiber::isStarted - Determines if the fiber has started
    • Fiber::isSuspended - Determines if the fiber is suspended
    • Fiber::isTerminated - Determines if the fiber has terminated
    • Fiber::resume - Resumes execution of the fiber with a value
    • Fiber::start - Start execution of the fiber
    • Fiber::suspend - Suspends execution of the current fiber
    • Fiber::throw - Resumes execution of the fiber with an exception
    • Fiber::__construct - Creates a new Fiber instance
    • FiberError::__construct - Constructor to disallow direct instantiation
    • file - Reads entire file into an array
    • file:// - Accessing local filesystem
    • fileatime - Gets last access time of file
    • filectime - Gets inode change time of file
    • filegroup - Gets file group
    • fileinode - Gets file inode
    • filemtime - Gets file modification time
    • fileowner - Gets file owner
    • fileperms - Gets file permissions
    • filesize - Gets file size
    • 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 - Gets file type
    • file_exists - Checks whether a file or directory exists
    • file_get_contents - Reads entire file into a string
    • file_put_contents - Write data to a file
    • 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 - Checks if variable of specified type exists
    • filter_id - Returns the filter ID belonging to a named filter
    • filter_input - Gets a specific external variable by name and optionally filters it
    • filter_input_array - Gets external variables and optionally filters them
    • filter_list - Returns a list of all supported filters
    • filter_var - Filters a variable with a specified filter
    • filter_var_array - Gets multiple variables and optionally filters them
    • finfo::buffer - Alias of finfo_buffer()
    • finfo::file - Alias of finfo_file()
    • finfo::set_flags - Alias of finfo_set_flags()
    • finfo::__construct - Alias of finfo_open
    • finfo_close - Close finfo instance
    • finfo_open - Create a new finfo instance
    • floatval - Get float value of a variable
    • flock - Portable advisory file locking
    • floor - Round fractions down
    • flush - Flush system output buffer
    • fmod - Returns the floating point remainder (modulo) of the division of the arguments
    • fnmatch - Match filename against a pattern
    • fopen - Opens file or URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Output all remaining data on a file pointer
    • fpm_get_status - Returns the current FPM pool status
    • fprintf - Write a formatted string to a stream
    • fputcsv - Format line as CSV and write to file pointer
    • fputs - Alias of fwrite
    • fread - Binary-safe file read
    • frenchtojd - Converts a date from the French Republican Calendar to a Julian Day Count
    • fscanf - Parses input from a file according to a format
    • fseek - Seeks on a file pointer
    • fsockopen - Open Internet or Unix domain socket connection
    • fstat - Gets information about a file using an open file pointer
    • fsync - Synchronizes changes to the file (including meta-data)
    • ftell - Returns the current position of the file read/write pointer
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - Accessing FTP(s) URLs
    • FTP context options - FTP context option listing
    • ftp_alloc - Allocates space for a file to be uploaded
    • ftp_append - Append the contents of a file to another file on the FTP server
    • ftp_cdup - Changes to the parent directory
    • ftp_chdir - Changes the current directory on a FTP server
    • ftp_chmod - Set permissions on a file via FTP
    • ftp_close - Closes an FTP connection
    • ftp_connect - Opens an FTP connection
    • ftp_delete - Deletes a file on the FTP server
    • ftp_exec - Requests execution of a command on the FTP server
    • ftp_fget - Downloads a file from the FTP server and saves to an open file
    • ftp_fput - Uploads from an open file to the FTP server
    • ftp_get - Downloads a file from the FTP server
    • ftp_get_option - Retrieves various runtime behaviours of the current FTP connection
    • ftp_login - Logs in to an FTP connection
    • ftp_mdtm - Returns the last modified time of the given file
    • ftp_mkdir - Creates a directory
    • ftp_mlsd - Returns a list of files in the given directory
    • ftp_nb_continue - Continues retrieving/sending a file (non-blocking)
    • ftp_nb_fget - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput - Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put - Stores a file on the FTP server (non-blocking)
    • ftp_nlist - Returns a list of files in the given directory
    • ftp_pasv - Turns passive mode on or off
    • ftp_put - Uploads a file to the FTP server
    • ftp_pwd - Returns the current directory name
    • ftp_quit - Alias of ftp_close
    • ftp_raw - Sends an arbitrary command to an FTP server
    • ftp_rawlist - Returns a detailed list of files in the given directory
    • ftp_rename - Renames a file or a directory on the FTP server
    • ftp_rmdir - Removes a directory
    • ftp_set_option - Set miscellaneous runtime FTP options
    • ftp_site - Sends a SITE command to the server
    • ftp_size - Returns the size of the given file
    • ftp_ssl_connect - Opens a Secure SSL-FTP connection
    • ftp_systype - Returns the system type identifier of the remote FTP server
    • ftruncate - Truncates a file to a given length
    • function_exists - Return true if the given function has been defined
    • func_get_arg - Return an item from the argument list
    • func_get_args - Returns an array comprising a function's argument list
    • func_num_args - Returns the number of arguments passed to the function
    • fwrite - Binary-safe file write
  • 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 - Retrieve information about the currently installed GD library
    • 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 - Get the yielded value
    • Generator::getReturn - Get the return value of a generator
    • Generator::key - Get the yielded key
    • Generator::next - Resume execution of the generator
    • Generator::rewind - Rewind the iterator
    • Generator::send - Send a value to the generator
    • Generator::throw - Throw an exception into the generator
    • Generator::valid - Check if the iterator has been closed
    • Generator::__wakeup - Serialize callback
    • geoip_asnum_by_name - Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name - Get the two letter continent code
    • geoip_country_code3_by_name - Get the three letter country code
    • geoip_country_code_by_name - Get the two letter country code
    • geoip_country_name_by_name - Get the full country name
    • geoip_database_info - Get GeoIP Database information
    • geoip_db_avail - Determine if GeoIP Database is available
    • geoip_db_filename - Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info - Returns detailed information about all GeoIP database types
    • geoip_domain_by_name - Get the second level domain name
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name - Get the Internet connection speed
    • geoip_org_by_name - Get the organization name
    • geoip_record_by_name - Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name - Get the country code and region
    • geoip_region_name_by_code - Returns the region name for some country and region code combo
    • geoip_setup_custom_directory - Set a custom directory for the GeoIP database
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • getallheaders - Fetch all HTTP request headers
    • getcwd - Gets the current working directory
    • getdate - Get date/time information
    • getenv - Gets the value of a single or all environment variables
    • gethostbyaddr - Get the Internet host name corresponding to a given IP address
    • gethostbyname - Get the IPv4 address corresponding to a given Internet host name
    • gethostbynamel - Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname - Gets the host name
    • getimagesize - Get the size of an image
    • getimagesizefromstring - Get the size of an image from a string
    • getlastmod - Gets time of last page modification
    • getmxrr - Get MX records corresponding to a given Internet host name
    • getmygid - Get PHP script owner's GID
    • getmyinode - Gets the inode of the current script
    • getmypid - Gets PHP's process ID
    • getmyuid - Gets PHP script owner's UID
    • getopt - Gets options from the command line argument list
    • getprotobyname - Get protocol number associated with protocol name
    • getprotobynumber - Get protocol name associated with protocol number
    • getrandmax - Show largest possible random value
    • getrusage - Gets the current resource usages
    • getservbyname - Get port number associated with an Internet service and protocol
    • getservbyport - Get Internet service which corresponds to port and protocol
    • getSession - Connect to a MySQL server
    • gettext - Lookup a message in the current domain
    • gettimeofday - Get current time
    • gettype - Get the type of a variable
    • get_browser - Tells what the user's browser is capable of
    • get_called_class - The "Late Static Binding" class name
    • get_cfg_var - Gets the value of a PHP configuration option
    • get_class - Returns the name of the class of an object
    • get_class_methods - Gets the class methods' names
    • get_class_vars - Get the default properties of the class
    • get_current_user - Gets the name of the owner of the current PHP script
    • get_debug_type - Gets the type name of a variable in a way that is suitable for debugging
    • get_declared_classes - Returns an array with the name of the defined classes
    • get_declared_interfaces - Returns an array of all declared interfaces
    • get_declared_traits - Returns an array of all declared traits
    • get_defined_constants - Returns an associative array with the names of all the constants and their values
    • get_defined_functions - Returns an array of all defined functions
    • get_defined_vars - Returns an array of all defined variables
    • get_extension_funcs - Returns an array with the names of the functions of a module
    • get_headers - Fetches all the headers sent by the server in response to an HTTP request
    • get_html_translation_table - Returns the translation table used by htmlspecialchars and htmlentities
    • get_included_files - Returns an array with the names of included or required files
    • get_include_path - Gets the current include_path configuration option
    • get_loaded_extensions - Returns an array with the names of all modules compiled and loaded
    • get_magic_quotes_gpc - Gets the current configuration setting of magic_quotes_gpc
    • get_magic_quotes_runtime - Gets the current active configuration setting of magic_quotes_runtime
    • get_mangled_object_vars - Returns an array of mangled object properties
    • get_meta_tags - Extracts all meta tag content attributes from a file and returns an array
    • get_object_vars - Gets the properties of the given object
    • get_parent_class - Retrieves the parent class name for object or class
    • get_required_files - Alias of get_included_files
    • get_resources - Returns active resources
    • get_resource_id - Returns an integer identifier for the given resource
    • get_resource_type - Returns the resource type
    • glob - Find pathnames matching a pattern
    • 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 of Gmagick::writeimage
    • Gmagick::writeimage - Writes an image to the specified filename
    • Gmagick::__construct - The Gmagick constructor
    • GmagickDraw::annotate - Draws text on the image
    • GmagickDraw::arc - Draws an arc
    • GmagickDraw::bezier - Draws a bezier curve
    • GmagickDraw::ellipse - Draws an ellipse on the image
    • GmagickDraw::getfillcolor - Returns the fill color
    • GmagickDraw::getfillopacity - Returns the opacity used when drawing
    • GmagickDraw::getfont - Returns the font
    • GmagickDraw::getfontsize - Returns the font pointsize
    • GmagickDraw::getfontstyle - Returns the font style
    • GmagickDraw::getfontweight - Returns the font weight
    • GmagickDraw::getstrokecolor - Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity - Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth - Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration - Returns the text decoration
    • GmagickDraw::gettextencoding - Returns the code set used for text annotations
    • GmagickDraw::line - Draws a line
    • GmagickDraw::point - Draws a point
    • GmagickDraw::polygon - Draws a polygon
    • GmagickDraw::polyline - Draws a polyline
    • GmagickDraw::rectangle - Draws a rectangle
    • GmagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle - Draws a rounded rectangle
    • GmagickDraw::scale - Adjusts the scaling factor
    • GmagickDraw::setfillcolor - Sets the fill color to be used for drawing filled objects
    • GmagickDraw::setfillopacity - The setfillopacity purpose
    • GmagickDraw::setfont - Sets the fully-specified font to use when annotating with text
    • GmagickDraw::setfontsize - Sets the font pointsize to use when annotating with text
    • GmagickDraw::setfontstyle - Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight - Sets the font weight
    • GmagickDraw::setstrokecolor - Sets the color used for stroking object outlines
    • GmagickDraw::setstrokeopacity - Specifies the opacity of stroked object outlines
    • GmagickDraw::setstrokewidth - Sets the width of the stroke used to draw object outlines
    • GmagickDraw::settextdecoration - Specifies a decoration
    • GmagickDraw::settextencoding - Specifies the text code set
    • GmagickPixel::getcolor - Returns the color
    • GmagickPixel::getcolorcount - Returns the color count associated with this color
    • GmagickPixel::getcolorvalue - Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor - Sets the color
    • GmagickPixel::setcolorvalue - Sets the normalized value of one of the channels
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - Format a GMT/UTC date/time
    • gmmktime - Get Unix timestamp for a GMT date
    • 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 of 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 - Format a GMT/UTC time/date according to locale settings
    • gnupg_adddecryptkey - Add a key for decryption
    • gnupg_addencryptkey - Add a key for encryption
    • gnupg_addsignkey - Add a key for signing
    • gnupg_cleardecryptkeys - Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys - Removes all keys which were set for encryption before
    • gnupg_clearsignkeys - Removes all keys which were set for signing before
    • gnupg_decrypt - Decrypts a given text
    • gnupg_decryptverify - Decrypts and verifies a given text
    • gnupg_deletekey - Delete a key from the keyring
    • gnupg_encrypt - Encrypts a given text
    • gnupg_encryptsign - Encrypts and signs a given text
    • gnupg_export - Exports a key
    • gnupg_getengineinfo - Returns the engine info
    • gnupg_geterror - Returns the errortext, if a function fails
    • gnupg_geterrorinfo - Returns the error info
    • gnupg_getprotocol - Returns the currently active protocol for all operations
    • gnupg_gettrustlist - Search the trust items
    • gnupg_import - Imports a key
    • gnupg_init - Initialize a connection
    • gnupg_keyinfo - Returns an array with information about all keys that matches the given pattern
    • gnupg_listsignatures - List key signatures
    • gnupg_setarmor - Toggle armored output
    • gnupg_seterrormode - Sets the mode for error_reporting
    • gnupg_setsignmode - Sets the mode for signing
    • gnupg_sign - Signs a given text
    • gnupg_verify - Verifies a signed text
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
    • grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
    • grapheme_strlen - Get string length in grapheme units
    • grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack
    • grapheme_substr - Return part of a string
    • gregoriantojd - Converts a Gregorian date to Julian Day Count
    • gzclose - Close an open gz-file pointer
    • gzcompress - Compress a string
    • gzdecode - Decodes a gzip compressed string
    • gzdeflate - Deflate a string
    • gzencode - Create a gzip compressed string
    • gzeof - Test for EOF on a gz-file pointer
    • gzfile - Read entire gz-file into an array
    • gzgetc - Get character from gz-file pointer
    • gzgets - Get line from file pointer
    • gzgetss - Get line from gz-file pointer and strip HTML tags
    • gzinflate - Inflate a deflated string
    • gzopen - Open gz-file
    • gzpassthru - Output all remaining data on a gz-file pointer
    • gzputs - Alias of gzwrite
    • gzread - Binary-safe gz-file read
    • gzrewind - Rewind the position of a gz-file pointer
    • gzseek - Seek on a gz-file pointer
    • gztell - Tell gz-file pointer read/write position
    • gzuncompress - Uncompress a compressed string
    • gzwrite - Binary-safe gz-file write
  • h
    • hash - Generate a hash value (message digest)
    • HashContext::__construct - Private constructor to disallow direct instantiation
    • HashContext::__serialize - Serializes the HashContext object
    • HashContext::__unserialize - Deserializes the data parameter into a HashContext object
    • hash_algos - Return a list of registered hashing algorithms
    • hash_copy - Copy hashing context
    • hash_equals - Timing attack safe string comparison
    • hash_file - Generate a hash value using the contents of a given file
    • hash_final - Finalize an incremental hash and return resulting digest
    • hash_hkdf - Generate a HKDF key derivation of a supplied key input
    • hash_hmac - Generate a keyed hash value using the HMAC method
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_init - Initialize an incremental hashing context
    • hash_pbkdf2 - Generate a PBKDF2 key derivation of a supplied password
    • hash_update - Pump data into an active hashing context
    • hash_update_file - Pump data into an active hashing context from a file
    • hash_update_stream - Pump data into an active hashing context from an open stream
    • header - Send a raw HTTP header
    • headers_list - Returns a list of response headers sent (or ready to send)
    • headers_sent - Checks if or where headers have been sent
    • header_register_callback - Call a header function
    • header_remove - Remove previously set headers
    • hebrev - Convert logical Hebrew text to visual text
    • hebrevc - Convert logical Hebrew text to visual text with newline conversion
    • hex2bin - Decodes a hexadecimally encoded binary string
    • hexdec - Hexadecimal to decimal
    • highlight_file - Syntax highlighting of a file
    • highlight_string - Syntax highlighting of a string
    • hrtime - Get the system's high resolution time
    • HRTime\PerformanceCounter::getFrequency - Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks - Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince - Ticks elapsed since the given value
    • HRTime\StopWatch::getElapsedTicks - Get elapsed ticks for all intervals
    • HRTime\StopWatch::getElapsedTime - Get elapsed time for all intervals
    • HRTime\StopWatch::getLastElapsedTicks - Get elapsed ticks for the last interval
    • HRTime\StopWatch::getLastElapsedTime - Get elapsed time for the last interval
    • HRTime\StopWatch::isRunning - Whether the measurement is running
    • HRTime\StopWatch::start - Start time measurement
    • HRTime\StopWatch::stop - Stop time measurement
    • htmlentities - Convert all applicable characters to HTML entities
    • htmlspecialchars - Convert special characters to HTML entities
    • htmlspecialchars_decode - Convert special HTML entities back to characters
    • html_entity_decode - Convert HTML entities to their corresponding characters
    • http:// - Accessing HTTP(s) URLs
    • HTTP context options - HTTP context option listing
    • http_build_query - Generate URL-encoded query string
    • http_response_code - Get or Set the HTTP response code
    • hypot - Calculate the length of the hypotenuse of a right-angle triangle
  • i
    • ibase_add_user - Add a user to a security database
    • ibase_affected_rows - Return the number of rows that were affected by the previous query
    • ibase_backup - Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add - Add data into a newly created blob
    • ibase_blob_cancel - Cancel creating blob
    • ibase_blob_close - Close blob
    • ibase_blob_create - Create a new blob for adding data
    • ibase_blob_echo - Output blob contents to browser
    • ibase_blob_get - Get len bytes data from open blob
    • ibase_blob_import - Create blob, copy file in it, and close it
    • ibase_blob_info - Return blob length and other useful info
    • ibase_blob_open - Open blob for retrieving data parts
    • ibase_close - Close a connection to an InterBase database
    • ibase_commit - Commit a transaction
    • ibase_commit_ret - Commit a transaction without closing it
    • ibase_connect - Open a connection to a database
    • ibase_db_info - Request statistics about a database
    • ibase_delete_user - Delete a user from a security database
    • ibase_drop_db - Drops a database
    • ibase_errcode - Return an error code
    • ibase_errmsg - Return error messages
    • ibase_execute - Execute a previously prepared query
    • ibase_fetch_assoc - Fetch a result row from a query as an associative array
    • ibase_fetch_object - Get an object from a InterBase database
    • ibase_fetch_row - Fetch a row from an InterBase database
    • ibase_field_info - Get information about a field
    • ibase_free_event_handler - Cancels a registered event handler
    • ibase_free_query - Free memory allocated by a prepared query
    • ibase_free_result - Free a result set
    • ibase_gen_id - Increments the named generator and returns its new value
    • ibase_maintain_db - Execute a maintenance command on the database server
    • ibase_modify_user - Modify a user to a security database
    • ibase_name_result - Assigns a name to a result set
    • ibase_num_fields - Get the number of fields in a result set
    • ibase_num_params - Return the number of parameters in a prepared query
    • ibase_param_info - Return information about a parameter in a prepared query
    • ibase_pconnect - Open a persistent connection to an InterBase database
    • ibase_prepare - Prepare a query for later binding of parameter placeholders and execution
    • ibase_query - Execute a query on an InterBase database
    • ibase_restore - Initiates a restore task in the service manager and returns immediately
    • ibase_rollback - Roll back a transaction
    • ibase_rollback_ret - Roll back a transaction without closing it
    • ibase_server_info - Request information about a database server
    • ibase_service_attach - Connect to the service manager
    • ibase_service_detach - Disconnect from the service manager
    • ibase_set_event_handler - Register a callback function to be called when events are posted
    • ibase_trans - Begin a transaction
    • ibase_wait_event - Wait for an event to be posted by the database
    • iconv - Convert a string from one character encoding to another
    • iconv_get_encoding - Retrieve internal configuration variables of iconv extension
    • 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 - Set current setting for character encoding conversion
    • 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 - Format a local time/date part as 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 - Set whether a client disconnect should abort script execution
    • image2wbmp - Output image to browser or file
    • imageaffine - Return an image containing the affine transformed src image, using an optional clipping area
    • imageaffinematrixconcat - Concatenate two affine transformation matrices
    • imageaffinematrixget - Get an affine transformation matrix
    • imagealphablending - Set the blending mode for an image
    • imageantialias - Should antialias functions be used or not
    • imagearc - Draws an arc
    • imageavif - Output image to browser or file
    • imagebmp - Output a BMP image to browser or file
    • imagechar - Draw a character horizontally
    • imagecharup - Draw a character vertically
    • imagecolorallocate - Allocate a color for an image
    • imagecolorallocatealpha - Allocate a color for an image
    • imagecolorat - Get the index of the color of a pixel
    • imagecolorclosest - Get the index of the closest color to the specified color
    • imagecolorclosestalpha - Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb - Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate - De-allocate a color for an image
    • imagecolorexact - Get the index of the specified color
    • imagecolorexactalpha - Get the index of the specified color + alpha
    • imagecolormatch - Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve - Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha - Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset - Set the color for the specified palette index
    • imagecolorsforindex - Get the colors for an index
    • imagecolorstotal - Find out the number of colors in an image's palette
    • imagecolortransparent - Define a color as transparent
    • imageconvolution - Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy - Copy part of an image
    • imagecopymerge - Copy and merge part of an image
    • imagecopymergegray - Copy and merge part of an image with gray scale
    • imagecopyresampled - Copy and resize part of an image with resampling
    • imagecopyresized - Copy and resize part of an image
    • imagecreate - Create a new palette based image
    • imagecreatefromavif - Create a new image from file or URL
    • imagecreatefrombmp - Create a new image from file or 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 - Create a new image from file or URL
    • imagecreatefromjpeg - Create a new image from file or URL
    • imagecreatefrompng - Create a new image from file or URL
    • imagecreatefromstring - Create a new image from the image stream in the string
    • imagecreatefromtga - Create a new image from file or URL
    • imagecreatefromwbmp - Create a new image from file or URL
    • imagecreatefromwebp - Create a new image from file or URL
    • imagecreatefromxbm - Create a new image from file or URL
    • imagecreatefromxpm - Create a new image from file or URL
    • imagecreatetruecolor - Create a new true color image
    • imagecrop - Crop an image to the given rectangle
    • imagecropauto - Crop an image automatically using one of the available modes
    • imagedashedline - Draw a dashed line
    • imagedestroy - Destroy an image
    • imageellipse - Draw an ellipse
    • imagefill - Flood fill
    • imagefilledarc - Draw a partial arc and fill it
    • imagefilledellipse - Draw a filled ellipse
    • imagefilledpolygon - Draw a filled polygon
    • imagefilledrectangle - Draw a filled rectangle
    • imagefilltoborder - Flood fill to specific color
    • imagefilter - Applies a filter to an image
    • imageflip - Flips an image using a given mode
    • imagefontheight - Get font height
    • imagefontwidth - Get font width
    • imageftbbox - Give the bounding box of a text using fonts via freetype2
    • imagefttext - Write text to the image using fonts using FreeType 2
    • imagegammacorrect - Apply a gamma correction to a GD image
    • imagegd - Output GD image to browser or file
    • imagegd2 - Output GD2 image to browser or file
    • imagegetclip - Get the clipping rectangle
    • imagegetinterpolation - Get the interpolation method
    • imagegif - Output image to browser or file
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - Enable or disable interlace
    • imageistruecolor - Finds whether an image is a truecolor image
    • imagejpeg - Output image to browser or file
    • imagelayereffect - Set the alpha blending flag to use layering effects
    • imageline - Draw a line
    • imageloadfont - Load a new font
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - Copy the palette from one image to another
    • imagepalettetotruecolor - Converts a palette based image to true color
    • imagepng - Output a PNG image to either the browser or a file
    • imagepolygon - Draws a polygon
    • imagerectangle - Draw a rectangle
    • imageresolution - Get or set the resolution of the image
    • imagerotate - Rotate an image with a given angle
    • imagesavealpha - Whether to retain full alpha channel information when saving images
    • imagescale - Scale an image using the given new width and height
    • imagesetbrush - Set the brush image for line drawing
    • imagesetclip - Set the clipping rectangle
    • imagesetinterpolation - Set the interpolation method
    • imagesetpixel - Set a single pixel
    • imagesetstyle - Set the style for line drawing
    • imagesetthickness - Set the thickness for line drawing
    • imagesettile - Set the tile image for filling
    • imagestring - Draw a string horizontally
    • imagestringup - Draw a string vertically
    • imagesx - Get image width
    • imagesy - Get image height
    • imagetruecolortopalette - Convert a true color image to a palette image
    • imagettfbbox - Give the bounding box of a text using TrueType fonts
    • imagettftext - Write text to the image using TrueType fonts
    • imagetypes - Return the image types supported by this PHP build
    • imagewbmp - Output image to browser or file
    • imagewebp - Output a WebP image to browser or file
    • imagexbm - Output an XBM image to browser or file
    • image_type_to_extension - Get file extension for image type
    • image_type_to_mime_type - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • Imagick::adaptiveBlurImage - Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage - Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage - Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage - Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage - Adds new image to Imagick object image list
    • Imagick::addNoiseImage - Adds random noise to the image
    • Imagick::affineTransformImage - Transforms an image
    • Imagick::animateImages - Animates an image or images
    • Imagick::annotateImage - Annotates an image with text
    • Imagick::appendImages - Append a set of images
    • Imagick::autoLevelImage - Adjusts the levels of a particular image channel
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blueShiftImage - Mutes the colors of the image
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::brightnessContrastImage - Change the brightness and/or contrast of an image
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clampImage - Restricts the color range from 0 to the quantum depth.
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath - Clips along the named paths from the 8BIM profile, if present
    • Imagick::clipPathImage - Clips along the named paths from the 8BIM profile
    • Imagick::clone - Makes an exact copy of the Imagick object
    • Imagick::clutImage - Replaces colors in the image
    • Imagick::coalesceImages - Composites a set of images
    • Imagick::colorFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::colorizeImage - Blends the fill color with the image
    • Imagick::colorMatrixImage - Apply color transformation to an image
    • Imagick::combineImages - Combines one or more images into a single image
    • Imagick::commentImage - Adds a comment to your image
    • Imagick::compareImageChannels - Returns the difference in one or more images
    • Imagick::compareImageLayers - Returns the maximum bounding region between images
    • Imagick::compareImages - Compares an image to a reconstructed image
    • Imagick::compositeImage - Composite one image onto another
    • Imagick::contrastImage - Change the contrast of the image
    • Imagick::contrastStretchImage - Enhances the contrast of a color image
    • Imagick::convolveImage - Applies a custom convolution kernel to the image
    • Imagick::count - Get the number of images
    • Imagick::cropImage - Extracts a region of the image
    • Imagick::cropThumbnailImage - Creates a crop thumbnail
    • Imagick::current - Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage - Displaces an image's colormap
    • Imagick::decipherImage - Deciphers an image
    • Imagick::deconstructImages - Returns certain pixel differences between images
    • Imagick::deleteImageArtifact - Delete image artifact
    • Imagick::deleteImageProperty - Deletes an image property
    • Imagick::deskewImage - Removes skew from the image
    • Imagick::despeckleImage - Reduces the speckle noise in an image
    • Imagick::destroy - Destroys the Imagick object
    • Imagick::displayImage - Displays an image
    • Imagick::displayImages - Displays an image or image sequence
    • Imagick::distortImage - Distorts an image using various distortion methods
    • Imagick::drawImage - Renders the ImagickDraw object on the current image
    • Imagick::edgeImage - Enhance edges within the image
    • Imagick::embossImage - Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage - Enciphers an image
    • Imagick::enhanceImage - Improves the quality of a noisy image
    • Imagick::equalizeImage - Equalizes the image histogram
    • Imagick::evaluateImage - Applies an expression to an image
    • Imagick::exportImagePixels - Exports raw image pixels
    • Imagick::extentImage - Set image size
    • Imagick::filter - Applies a custom convolution kernel to the image
    • Imagick::flattenImages - Merges a sequence of images
    • Imagick::flipImage - Creates a vertical mirror image
    • Imagick::floodFillPaintImage - Changes the color value of any pixel that matches target
    • Imagick::flopImage - Creates a horizontal mirror image
    • Imagick::forwardFourierTransformImage - Implements the discrete Fourier transform (DFT)
    • Imagick::frameImage - Adds a simulated three-dimensional border
    • Imagick::functionImage - Applies a function on the image
    • Imagick::fxImage - Evaluate expression for each pixel in the image
    • Imagick::gammaImage - Gamma-corrects an image
    • Imagick::gaussianBlurImage - Blurs an image
    • Imagick::getColorspace - Gets the colorspace
    • Imagick::getCompression - Gets the object compression type
    • Imagick::getCompressionQuality - Gets the object compression quality
    • Imagick::getCopyright - Returns the ImageMagick API copyright as a string
    • Imagick::getFilename - The filename associated with an image sequence
    • Imagick::getFont - Gets font
    • Imagick::getFormat - Returns the format of the Imagick object
    • Imagick::getGravity - Gets the gravity
    • Imagick::getHomeURL - Returns the ImageMagick home URL
    • Imagick::getImage - Returns a new Imagick object
    • Imagick::getImageAlphaChannel - Checks if the image has an alpha channel
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageAttribute - Returns a named attribute
    • Imagick::getImageBackgroundColor - Returns the image background color
    • Imagick::getImageBlob - Returns the image sequence as a blob
    • Imagick::getImageBluePrimary - Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor - Returns the image border color
    • Imagick::getImageChannelDepth - Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion - Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions - Gets channel distortions
    • Imagick::getImageChannelExtrema - Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis - The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean - Gets the mean and standard deviation
    • Imagick::getImageChannelRange - Gets channel range
    • Imagick::getImageChannelStatistics - Returns statistics for each channel in the image
    • Imagick::getImageClipMask - Gets image clip mask
    • Imagick::getImageColormapColor - Returns the color of the specified colormap index
    • Imagick::getImageColors - Gets the number of unique colors in the image
    • Imagick::getImageColorspace - Gets the image colorspace
    • Imagick::getImageCompose - Returns the composite operator associated with the image
    • Imagick::getImageCompression - Gets the current image's compression type
    • Imagick::getImageCompressionQuality - Gets the current image's compression quality
    • Imagick::getImageDelay - Gets the image delay
    • Imagick::getImageDepth - Gets the image depth
    • Imagick::getImageDispose - Gets the image disposal method
    • Imagick::getImageDistortion - Compares an image to a reconstructed image
    • Imagick::getImageExtrema - Gets the extrema for the image
    • Imagick::getImageFilename - Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat - Returns the format of a particular image in a sequence
    • Imagick::getImageGamma - Gets the image gamma
    • Imagick::getImageGeometry - Gets the width and height as an associative array
    • Imagick::getImageGravity - Gets the image gravity
    • Imagick::getImageGreenPrimary - Returns the chromaticy green primary point
    • Imagick::getImageHeight - Returns the image height
    • Imagick::getImageHistogram - Gets the image histogram
    • Imagick::getImageIndex - Gets the index of the current active image
    • Imagick::getImageInterlaceScheme - Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod - Returns the interpolation method
    • Imagick::getImageIterations - Gets the image iterations
    • Imagick::getImageLength - Returns the image length in bytes
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageMimeType - Returns the image mime-type
    • Imagick::getImageOrientation - Gets the image orientation
    • Imagick::getImagePage - Returns the page geometry
    • Imagick::getImagePixelColor - Returns the color of the specified pixel
    • Imagick::getImageProfile - Returns the named image profile
    • Imagick::getImageProfiles - Returns the image profiles
    • Imagick::getImageProperties - Returns the image properties
    • Imagick::getImageProperty - Returns the named image property
    • Imagick::getImageRedPrimary - Returns the chromaticity red primary point
    • Imagick::getImageRegion - Extracts a region of the image
    • Imagick::getImageRenderingIntent - Gets the image rendering intent
    • Imagick::getImageResolution - Gets the image X and Y resolution
    • Imagick::getImagesBlob - Returns all image sequences as a blob
    • Imagick::getImageScene - Gets the image scene
    • Imagick::getImageSignature - Generates an SHA-256 message digest
    • Imagick::getImageSize - Returns the image length in bytes
    • Imagick::getImageTicksPerSecond - Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity - Gets the image total ink density
    • Imagick::getImageType - Gets the potential image type
    • Imagick::getImageUnits - Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod - Returns the virtual pixel method
    • Imagick::getImageWhitePoint - Returns the chromaticity white point
    • Imagick::getImageWidth - Returns the image width
    • Imagick::getInterlaceScheme - Gets the object interlace scheme
    • Imagick::getIteratorIndex - Gets the index of the current active image
    • Imagick::getNumberImages - Returns the number of images in the object
    • Imagick::getOption - Returns a value associated with the specified key
    • Imagick::getPackageName - Returns the ImageMagick package name
    • Imagick::getPage - Returns the page geometry
    • Imagick::getPixelIterator - Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator - Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize - Gets point size
    • Imagick::getQuantum - Returns the ImageMagick quantum range
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getRegistry - Get a StringRegistry entry
    • Imagick::getReleaseDate - Returns the ImageMagick release date
    • Imagick::getResource - Returns the specified resource's memory usage
    • Imagick::getResourceLimit - Returns the specified resource limit
    • Imagick::getSamplingFactors - Gets the horizontal and vertical sampling factor
    • Imagick::getSize - Returns the size associated with the Imagick object
    • Imagick::getSizeOffset - Returns the size offset
    • Imagick::getVersion - Returns the ImageMagick API version
    • Imagick::haldClutImage - Replaces colors in the image
    • Imagick::hasNextImage - Checks if the object has more images
    • Imagick::hasPreviousImage - Checks if the object has a previous image
    • Imagick::identifyFormat - Formats a string with image details
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::inverseFourierTransformImage - Implements the inverse discrete Fourier transform (DFT)
    • Imagick::labelImage - Adds a label to an image
    • Imagick::levelImage - Adjusts the levels of an image
    • Imagick::linearStretchImage - Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage - Animates an image or images
    • Imagick::listRegistry - List all the registry settings
    • Imagick::magnifyImage - Scales an image proportionally 2x
    • Imagick::mapImage - Replaces the colors of an image with the closest color from a reference image
    • Imagick::matteFloodfillImage - Changes the transparency value of a color
    • Imagick::medianFilterImage - Applies a digital filter
    • Imagick::mergeImageLayers - Merges image layers
    • Imagick::minifyImage - Scales an image proportionally to half its size
    • Imagick::modulateImage - Control the brightness, saturation, and hue
    • Imagick::montageImage - Creates a composite image
    • Imagick::morphImages - Method morphs a set of images
    • Imagick::morphology - Applies a user supplied kernel to the image according to the given morphology method.
    • Imagick::mosaicImages - Forms a mosaic from images
    • Imagick::motionBlurImage - Simulates motion blur
    • Imagick::negateImage - Negates the colors in the reference image
    • Imagick::newImage - Creates a new image
    • Imagick::newPseudoImage - Creates a new image
    • Imagick::nextImage - Moves to the next image
    • Imagick::normalizeImage - Enhances the contrast of a color image
    • Imagick::oilPaintImage - Simulates an oil painting
    • Imagick::opaquePaintImage - Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers - Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage - Performs an ordered dither
    • Imagick::paintFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage - Change any pixel that matches color
    • Imagick::paintTransparentImage - Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage - Fetch basic attributes about the image
    • Imagick::pingImageBlob - Quickly fetch attributes
    • Imagick::pingImageFile - Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage - Simulates a Polaroid picture
    • Imagick::posterizeImage - Reduces the image to a limited number of color level
    • Imagick::previewImages - Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage - Move to the previous image in the object
    • Imagick::profileImage - Adds or removes a profile from an image
    • Imagick::quantizeImage - Analyzes the colors within a reference image
    • Imagick::quantizeImages - Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics - Returns an array representing the font metrics
    • Imagick::queryFonts - Returns the configured fonts
    • Imagick::queryFormats - Returns formats supported by Imagick
    • Imagick::radialBlurImage - Radial blurs an image
    • Imagick::raiseImage - Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage - Creates a high-contrast, two-color image
    • Imagick::readImage - Reads image from filename
    • Imagick::readImageBlob - Reads image from a binary string
    • Imagick::readImageFile - Reads image from open filehandle
    • Imagick::readimages - Reads image from an array of filenames
    • Imagick::recolorImage - Recolors image
    • Imagick::reduceNoiseImage - Smooths the contours of an image
    • Imagick::remapImage - Remaps image colors
    • Imagick::removeImage - Removes an image from the image list
    • Imagick::removeImageProfile - Removes the named image profile and returns it
    • Imagick::render - Renders all preceding drawing commands
    • Imagick::resampleImage - Resample image to desired resolution
    • Imagick::resetImagePage - Reset image page
    • Imagick::resizeImage - Scales an image
    • Imagick::rollImage - Offsets an image
    • Imagick::rotateImage - Rotates an image
    • Imagick::rotationalBlurImage - Rotational blurs an image
    • Imagick::roundCorners - Rounds image corners
    • Imagick::sampleImage - Scales an image with pixel sampling
    • Imagick::scaleImage - Scales the size of an image
    • Imagick::segmentImage - Segments an image
    • Imagick::selectiveBlurImage - Selectively blur an image within a contrast threshold
    • Imagick::separateImageChannel - Separates a channel from the image
    • Imagick::sepiaToneImage - Sepia tones an image
    • Imagick::setBackgroundColor - Sets the object's default background color
    • Imagick::setColorspace - Set colorspace
    • Imagick::setCompression - Sets the object's default compression type
    • Imagick::setCompressionQuality - Sets the object's default compression quality
    • Imagick::setFilename - Sets the filename before you read or write the image
    • Imagick::setFirstIterator - Sets the Imagick iterator to the first image
    • Imagick::setFont - Sets font
    • Imagick::setFormat - Sets the format of the Imagick object
    • Imagick::setGravity - Sets the gravity
    • Imagick::setImage - Replaces image in the object
    • Imagick::setImageAlphaChannel - Sets image alpha channel
    • Imagick::setImageArtifact - Set image artifact
    • Imagick::setImageAttribute - Sets an image attribute
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum - Sets the image bias
    • Imagick::setImageBluePrimary - Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor - Sets the image border color
    • Imagick::setImageChannelDepth - Sets the depth of a particular image channel
    • Imagick::setImageClipMask - Sets image clip mask
    • Imagick::setImageColormapColor - Sets the color of the specified colormap index
    • Imagick::setImageColorspace - Sets the image colorspace
    • Imagick::setImageCompose - Sets the image composite operator
    • Imagick::setImageCompression - Sets the image compression
    • Imagick::setImageCompressionQuality - Sets the image compression quality
    • Imagick::setImageDelay - Sets the image delay
    • Imagick::setImageDepth - Sets the image depth
    • Imagick::setImageDispose - Sets the image disposal method
    • Imagick::setImageExtent - Sets the image size
    • Imagick::setImageFilename - Sets the filename of a particular image
    • Imagick::setImageFormat - Sets the format of a particular image
    • Imagick::setImageGamma - Sets the image gamma
    • Imagick::setImageGravity - Sets the image gravity
    • Imagick::setImageGreenPrimary - Sets the image chromaticity green primary point
    • Imagick::setImageIndex - Set the iterator position
    • Imagick::setImageInterlaceScheme - Sets the image compression
    • Imagick::setImageInterpolateMethod - Sets the image interpolate pixel method
    • Imagick::setImageIterations - Sets the image iterations
    • Imagick::setImageMatte - Sets the image matte channel
    • Imagick::setImageMatteColor - Sets the image matte color
    • Imagick::setImageOpacity - Sets the image opacity level
    • Imagick::setImageOrientation - Sets the image orientation
    • Imagick::setImagePage - Sets the page geometry of the image
    • Imagick::setImageProfile - Adds a named profile to the Imagick object
    • Imagick::setImageProperty - Sets an image property
    • Imagick::setImageRedPrimary - Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent - Sets the image rendering intent
    • Imagick::setImageResolution - Sets the image resolution
    • Imagick::setImageScene - Sets the image scene
    • Imagick::setImageTicksPerSecond - Sets the image ticks-per-second
    • Imagick::setImageType - Sets the image type
    • Imagick::setImageUnits - Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod - Sets the image virtual pixel method
    • Imagick::setImageWhitePoint - Sets the image chromaticity white point
    • Imagick::setInterlaceScheme - Sets the image compression
    • Imagick::setIteratorIndex - Set the iterator position
    • Imagick::setLastIterator - Sets the Imagick iterator to the last image
    • Imagick::setOption - Set an option
    • Imagick::setPage - Sets the page geometry of the Imagick object
    • Imagick::setPointSize - Sets point size
    • Imagick::setProgressMonitor - Set a callback to be called during processing
    • Imagick::setRegistry - Sets the ImageMagick registry entry named key to value
    • Imagick::setResolution - Sets the image resolution
    • Imagick::setResourceLimit - Sets the limit for a particular resource
    • Imagick::setSamplingFactors - Sets the image sampling factors
    • Imagick::setSize - Sets the size of the Imagick object
    • Imagick::setSizeOffset - Sets the size and offset of the Imagick object
    • Imagick::setType - Sets the image type attribute
    • Imagick::shadeImage - Creates a 3D effect
    • Imagick::shadowImage - Simulates an image shadow
    • Imagick::sharpenImage - Sharpens an image
    • Imagick::shaveImage - Shaves pixels from the image edges
    • Imagick::shearImage - Creating a parallelogram
    • Imagick::sigmoidalContrastImage - Adjusts the contrast of an image
    • Imagick::sketchImage - Simulates a pencil sketch
    • Imagick::smushImages - Takes all images from the current image pointer to the end of the image list and smushs them
    • Imagick::solarizeImage - Applies a solarizing effect to the image
    • Imagick::sparseColorImage - Interpolates colors
    • Imagick::spliceImage - Splices a solid color into the image
    • Imagick::spreadImage - Randomly displaces each pixel in a block
    • Imagick::statisticImage - Modifies image using a statistics function
    • Imagick::steganoImage - Hides a digital watermark within the image
    • Imagick::stereoImage - Composites two images
    • Imagick::stripImage - Strips an image of all profiles and comments
    • Imagick::subImageMatch - Searches for a subimage in the current image and returns a similarity image
    • Imagick::swirlImage - Swirls the pixels about the center of the image
    • Imagick::textureImage - Repeatedly tiles the texture image
    • Imagick::thresholdImage - Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage - Changes the size of an image
    • Imagick::tintImage - Applies a color vector to each pixel in the image
    • Imagick::transformImage - Convenience method for setting crop size and the image geometry
    • Imagick::transformImageColorspace - Transforms an image to a new colorspace
    • Imagick::transparentPaintImage - Paints pixels transparent
    • Imagick::transposeImage - Creates a vertical mirror image
    • Imagick::transverseImage - Creates a horizontal mirror image
    • Imagick::trimImage - Remove edges from the image
    • Imagick::uniqueImageColors - Discards all but one of any pixel color
    • Imagick::unsharpMaskImage - Sharpens an image
    • Imagick::valid - Checks if the current item is valid
    • Imagick::vignetteImage - Adds vignette filter to the image
    • Imagick::waveImage - Applies wave filter to the image
    • Imagick::whiteThresholdImage - Force all pixels above the threshold into white
    • Imagick::writeImage - Writes an image to the specified filename
    • Imagick::writeImageFile - Writes an image to a filehandle
    • Imagick::writeImages - Writes an image or image sequence
    • Imagick::writeImagesFile - Writes frames to a filehandle
    • Imagick::__construct - The Imagick constructor
    • Imagick::__toString - Returns the image as a string
    • ImagickDraw::affine - Adjusts the current affine transformation matrix
    • ImagickDraw::annotation - Draws text on the image
    • ImagickDraw::arc - Draws an arc
    • ImagickDraw::bezier - Draws a bezier curve
    • ImagickDraw::circle - Draws a circle
    • ImagickDraw::clear - Clears the ImagickDraw
    • ImagickDraw::clone - Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color - Draws color on image
    • ImagickDraw::comment - Adds a comment
    • ImagickDraw::composite - Composites an image onto the current image
    • ImagickDraw::destroy - Frees all associated resources
    • ImagickDraw::ellipse - Draws an ellipse on the image
    • ImagickDraw::getClipPath - Obtains the current clipping path ID
    • ImagickDraw::getClipRule - Returns the current polygon fill rule
    • ImagickDraw::getClipUnits - Returns the interpretation of clip path units
    • ImagickDraw::getFillColor - Returns the fill color
    • ImagickDraw::getFillOpacity - Returns the opacity used when drawing
    • ImagickDraw::getFillRule - Returns the fill rule
    • ImagickDraw::getFont - Returns the font
    • ImagickDraw::getFontFamily - Returns the font family
    • ImagickDraw::getFontSize - Returns the font pointsize
    • ImagickDraw::getFontStretch - Gets the font stretch to use when annotating with text
    • ImagickDraw::getFontStyle - Returns the font style
    • ImagickDraw::getFontWeight - Returns the font weight
    • ImagickDraw::getGravity - Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias - Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor - Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray - Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset - Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap - Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin - Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit - Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity - Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth - Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment - Returns the text alignment
    • ImagickDraw::getTextAntialias - Returns the current text antialias setting
    • ImagickDraw::getTextDecoration - Returns the text decoration
    • ImagickDraw::getTextEncoding - Returns the code set used for text annotations
    • ImagickDraw::getTextInterlineSpacing - Gets the text interword spacing
    • ImagickDraw::getTextInterwordSpacing - Gets the text interword spacing
    • ImagickDraw::getTextKerning - Gets the text kerning
    • ImagickDraw::getTextUnderColor - Returns the text under color
    • ImagickDraw::getVectorGraphics - Returns a string containing vector graphics
    • ImagickDraw::line - Draws a line
    • ImagickDraw::matte - Paints on the image's opacity channel
    • ImagickDraw::pathClose - Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute - Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative - Draws an elliptical arc
    • ImagickDraw::pathFinish - Terminates the current path
    • ImagickDraw::pathLineToAbsolute - Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute - Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative - Draws a horizontal line
    • ImagickDraw::pathLineToRelative - Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute - Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative - Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute - Starts a new sub-path
    • ImagickDraw::pathMoveToRelative - Starts a new sub-path
    • ImagickDraw::pathStart - Declares the start of a path drawing list
    • ImagickDraw::point - Draws a point
    • ImagickDraw::polygon - Draws a polygon
    • ImagickDraw::polyline - Draws a polyline
    • ImagickDraw::pop - Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath - Terminates a clip path definition
    • ImagickDraw::popDefs - Terminates a definition list
    • ImagickDraw::popPattern - Terminates a pattern definition
    • ImagickDraw::push - Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath - Starts a clip path definition
    • ImagickDraw::pushDefs - Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern - Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle - Draws a rectangle
    • ImagickDraw::render - Renders all preceding drawing commands onto the image
    • ImagickDraw::resetVectorGraphics - Resets the vector graphics
    • ImagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle - Draws a rounded rectangle
    • ImagickDraw::scale - Adjusts the scaling factor
    • ImagickDraw::setClipPath - Associates a named clipping path with the image
    • ImagickDraw::setClipRule - Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits - Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor - Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL - Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule - Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont - Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily - Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize - Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch - Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle - Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight - Sets the font weight
    • ImagickDraw::setGravity - Sets the text placement gravity
    • ImagickDraw::setResolution - Sets the resolution
    • ImagickDraw::setStrokeAlpha - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias - Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor - Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray - Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset - Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap - Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin - Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit - Specifies the miter limit
    • ImagickDraw::setStrokeOpacity - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL - Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth - Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment - Specifies a text alignment
    • ImagickDraw::setTextAntialias - Controls whether text is antialiased
    • ImagickDraw::setTextDecoration - Specifies a decoration
    • ImagickDraw::setTextEncoding - Specifies the text code set
    • ImagickDraw::setTextInterlineSpacing - Sets the text interline spacing
    • ImagickDraw::setTextInterwordSpacing - Sets the text interword spacing
    • ImagickDraw::setTextKerning - Sets the text kerning
    • ImagickDraw::setTextUnderColor - Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics - Sets the vector graphics
    • ImagickDraw::setViewbox - Sets the overall canvas size
    • ImagickDraw::skewX - Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY - Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate - Applies a translation to the current coordinate system
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickKernel::addKernel - Attach another kernel to a kernel list
    • ImagickKernel::addUnityKernel - Adds a Unity Kernel to the kernel list
    • ImagickKernel::fromBuiltIn - Create a kernel from a builtin in kernel
    • ImagickKernel::fromMatrix - Create a kernel from a 2d matrix of values
    • ImagickKernel::getMatrix - Get the 2d matrix of values used in this kernel
    • ImagickKernel::scale - Scales a kernel list by the given amount
    • ImagickKernel::separate - Separates a linked set of kernels and returns an array of ImagickKernels
    • ImagickPixel::clear - Clears resources associated with this object
    • ImagickPixel::destroy - Deallocates resources associated with this object
    • ImagickPixel::getColor - Returns the color
    • ImagickPixel::getColorAsString - Returns the color as a string
    • ImagickPixel::getColorCount - Returns the color count associated with this color
    • ImagickPixel::getColorQuantum - Returns the color of the pixel in an array as Quantum values
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum - Gets the quantum value of a color in the ImagickPixel
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex - Gets the colormap index of the pixel wand
    • ImagickPixel::isPixelSimilar - Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum - Returns whether two colors differ by less than the specified distance
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorCount - Sets the color count associated with this color
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum - Sets the quantum value of a color element of the ImagickPixel
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::setIndex - Sets the colormap index of the pixel wand
    • ImagickPixel::__construct - The ImagickPixel constructor
    • ImagickPixelIterator::clear - Clear resources associated with a PixelIterator
    • ImagickPixelIterator::destroy - Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow - Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow - Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow - Returns the previous row
    • ImagickPixelIterator::newPixelIterator - Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator - Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator - Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow - Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow - Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow - Set the pixel iterator row
    • ImagickPixelIterator::syncIterator - Syncs the pixel iterator
    • ImagickPixelIterator::__construct - The ImagickPixelIterator constructor
    • imap_8bit - Convert an 8bit string to a quoted-printable string
    • imap_alerts - Returns all IMAP alert messages that have occurred
    • imap_append - Append a string message to a specified mailbox
    • imap_base64 - Decode BASE64 encoded text
    • imap_binary - Convert an 8bit string to a base64 string
    • imap_body - Read the message body
    • imap_bodystruct - Read the structure of a specified body section of a specific message
    • imap_check - Check current mailbox
    • imap_clearflag_full - Clears flags on messages
    • imap_close - Close an IMAP stream
    • imap_create - Alias of imap_createmailbox
    • imap_createmailbox - Create a new mailbox
    • imap_delete - Mark a message for deletion from current mailbox
    • imap_deletemailbox - Delete a mailbox
    • imap_errors - Returns all of the IMAP errors that have occurred
    • imap_expunge - Delete all messages marked for deletion
    • imap_fetchbody - Fetch a particular section of the body of the message
    • imap_fetchheader - Returns header for a message
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Read the structure of a particular message
    • imap_fetchtext - Alias of imap_body
    • imap_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • imap_getacl - Gets the ACL for a given mailbox
    • imap_getmailboxes - Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed - List all the subscribed mailboxes
    • imap_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • imap_header - Alias of imap_headerinfo
    • imap_headerinfo - Read the header of the message
    • imap_headers - Returns headers for all messages in a mailbox
    • imap_is_open - Check if the IMAP stream is still valid
    • imap_last_error - Gets the last IMAP error that occurred during this page request
    • imap_list - Read the list of mailboxes
    • imap_listmailbox - Alias of imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - Alias of imap_lsub
    • imap_lsub - List all the subscribed mailboxes
    • imap_mail - Send an email message
    • imap_mailboxmsginfo - Get information about the current mailbox
    • imap_mail_compose - Create a MIME message based on given envelope and body sections
    • imap_mail_copy - Copy specified messages to a mailbox
    • imap_mail_move - Move specified messages to a mailbox
    • imap_mime_header_decode - Decode MIME header elements
    • imap_msgno - Gets the message sequence number for the given UID
    • imap_mutf7_to_utf8 - Decode a modified UTF-7 string to UTF-8
    • imap_num_msg - Gets the number of messages in the current mailbox
    • imap_num_recent - Gets the number of recent messages in current mailbox
    • imap_open - Open an IMAP stream to a mailbox
    • imap_ping - Check if the IMAP stream is still active
    • imap_qprint - Convert a quoted-printable string to an 8 bit string
    • imap_rename - Alias of imap_renamemailbox
    • imap_renamemailbox - Rename an old mailbox to new mailbox
    • imap_reopen - Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist - Parses an address string
    • imap_rfc822_parse_headers - Parse mail headers from a string
    • imap_rfc822_write_address - Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody - Save a specific body section to a file
    • imap_scan - Alias of imap_listscan
    • imap_scanmailbox - Alias of imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a given mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • imap_sort - Gets and sort messages
    • imap_status - Returns status information on a mailbox
    • imap_subscribe - Subscribe to a mailbox
    • imap_thread - Returns a tree of threaded message
    • imap_timeout - Set or fetch imap timeout
    • imap_uid - This function returns the UID for the given message sequence number
    • imap_undelete - Unmark the message which is marked deleted
    • imap_unsubscribe - Unsubscribe from a mailbox
    • imap_utf7_decode - Decodes a modified UTF-7 encoded string
    • imap_utf7_encode - Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 - Converts MIME-encoded text to UTF-8
    • imap_utf8_to_mutf7 - Encode a UTF-8 string to modified UTF-7
    • implode - Join array elements with a string
    • inet_ntop - Converts a packed internet address to a human readable representation
    • inet_pton - Converts a human readable IP address to its packed in_addr representation
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • inflate_add - Incrementally inflate encoded data
    • inflate_get_read_len - Get number of bytes read so far
    • inflate_get_status - Get decompression status
    • inflate_init - Initialize an incremental inflate context
    • ini_alter - Alias of 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 - Checks if the interface has been defined
    • InternalIterator::current - Return the current element
    • InternalIterator::key - Return the key of the current element
    • InternalIterator::next - Move forward to next element
    • InternalIterator::rewind - Rewind the Iterator to the first element
    • InternalIterator::valid - Check if current position is valid
    • InternalIterator::__construct - Private constructor to disallow direct instantiation
    • IntlBreakIterator::createCharacterInstance - 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 - Get the integer value of a variable
    • in_array - Checks if a value exists in an array
    • ip2long - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags
    • isset - Determine if a variable is declared and is different than null
    • is_a - Checks whether the object is of a given type or subtype
    • is_array - Finds whether a variable is an array
    • is_bool - Finds out whether a variable is a boolean
    • is_callable - Verify that a value can be called as a function from the current scope.
    • is_countable - Verify that the contents of a variable is a countable value
    • is_dir - Tells whether the filename is a directory
    • is_double - Alias of is_float
    • is_executable - Tells whether the filename is executable
    • is_file - Tells whether the filename is a regular file
    • is_finite - Checks whether a float is finite
    • is_float - Finds whether the type of a variable is float
    • is_infinite - Checks whether a float is infinite
    • is_int - Find whether the type of a variable is integer
    • is_integer - Alias of is_int
    • is_iterable - Verify that the contents of a variable is an iterable value
    • is_link - Tells whether the filename is a symbolic link
    • is_long - Alias of is_int
    • is_nan - Checks whether a float is NAN
    • is_null - Finds whether a variable is null
    • is_numeric - Finds whether a variable is a number or a numeric string
    • is_object - Finds whether a variable is an object
    • is_readable - Tells whether a file exists and is readable
    • is_real - Alias of is_float
    • is_resource - Finds whether a variable is a resource
    • is_scalar - Finds whether a variable is a scalar
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Find whether the type of a variable is string
    • is_subclass_of - Checks if the object has this class as one of its parents or implements it
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - Tells whether the file was uploaded via HTTP POST
    • is_writable - Tells whether the filename is writable
    • is_writeable - Alias of is_writable
    • Iterator::current - Return the current element
    • Iterator::key - Return the key of the current element
    • Iterator::next - Move forward to next element
    • Iterator::rewind - Rewind the Iterator to the first element
    • Iterator::valid - Checks if current position is valid
    • IteratorAggregate::getIterator - Retrieve an external iterator
    • IteratorIterator::current - Get the current value
    • IteratorIterator::getInnerIterator - Get the inner iterator
    • IteratorIterator::key - Get the key of the current element
    • IteratorIterator::next - Forward to the next element
    • IteratorIterator::rewind - Rewind to the first element
    • IteratorIterator::valid - Checks if the iterator is valid
    • IteratorIterator::__construct - Create an iterator from anything that is traversable
    • iterator_apply - Call a function for every element in an iterator
    • iterator_count - Count the elements in an iterator
    • iterator_to_array - Copy the iterator into an array
  • j
    • jddayofweek - Returns the day of the week
    • jdmonthname - Returns a month name
    • jdtofrench - Converts a Julian Day Count to the French Republican Calendar
    • jdtogregorian - Converts Julian Day Count to Gregorian date
    • jdtojewish - Converts a Julian day count to a Jewish calendar date
    • jdtojulian - Converts a Julian Day Count to a Julian Calendar Date
    • jdtounix - Convert Julian Day to Unix timestamp
    • jewishtojd - Converts a date in the Jewish Calendar to Julian Day Count
    • join - Alias of implode
    • jpeg2wbmp - Convert JPEG image file to WBMP image file
    • JsonSerializable::jsonSerialize - Specify data which should be serialized to JSON
    • json_decode - Decodes a JSON string
    • json_encode - Returns the JSON representation of a value
    • json_last_error - Returns the last error occurred
    • json_last_error_msg - Returns the error string of the last json_encode() or json_decode() call
    • json_validate - Checks if a string contains valid JSON
    • juliantojd - Converts a Julian Calendar date to Julian Day Count
  • k
    • key - Fetch a key from an array
    • key_exists - Alias of array_key_exists
    • krsort - Sort an array by key in descending order
    • ksort - Sort an array by key in ascending order
  • l
    • lcfirst - Make a string's first character lowercase
    • lcg_value - Combined linear congruential generator
    • lchgrp - Changes group ownership of symlink
    • lchown - Changes user ownership of symlink
    • ldap_8859_to_t61 - Translate 8859 characters to t61 characters
    • ldap_add - Add entries to LDAP directory
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - Bind to LDAP directory
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - Alias of ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_connect_wallet - Connect to an LDAP server
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • ldap_count_entries - Count the number of entries in a search
    • ldap_count_references - Counts the number of references in a search result
    • ldap_delete - Delete an entry from a directory
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Convert DN to User Friendly Naming format
    • ldap_err2str - Convert LDAP error number into string error message
    • ldap_errno - Return the LDAP error number of the last LDAP command
    • ldap_error - Return the LDAP error message of the last LDAP command
    • ldap_escape - Escape a string for use in an LDAP filter or DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_sync - Performs an extended operation
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Splits DN into its component parts
    • ldap_first_attribute - Return first attribute
    • ldap_first_entry - Return first result id
    • ldap_first_reference - Return first reference
    • ldap_free_result - Free result memory
    • ldap_get_attributes - Get attributes from a search result entry
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Get all result entries
    • ldap_get_option - Get the current value for given option
    • ldap_get_values - Get all values from a result entry
    • ldap_get_values_len - Get all binary values from a result entry
    • ldap_list - Single-level search
    • ldap_modify - Alias of ldap_mod_replace
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Add attribute values to current attributes
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Delete attribute values from current attributes
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Replace attribute values with new ones
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Get the next attribute in result
    • ldap_next_entry - Get next result entry
    • ldap_next_reference - Get next reference
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extract information from reference entry
    • ldap_parse_result - Extract information from result
    • ldap_read - Read an entry
    • ldap_rename - Modify the name of an entry
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Search LDAP tree
    • ldap_set_option - Set the value of the given option
    • ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing
    • ldap_sort - Sort LDAP result entries on the client side
    • ldap_start_tls - Start TLS
    • ldap_t61_to_8859 - Translate t61 characters to 8859 characters
    • ldap_unbind - Unbind from LDAP directory
    • levenshtein - Calculate Levenshtein distance between two strings
    • libxml_clear_errors - 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 - Create a hard link
    • linkinfo - Gets information about a link
    • list - Assign variables as if they were an 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 - Get numeric formatting information
    • localtime - Get the local time
    • log - Natural logarithm
    • log1p - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
    • log10 - Base-10 logarithm
    • long2ip - Converts a long integer address into a string in (IPv4) Internet standard dotted format
    • lstat - Gives information about a file or symbolic link
    • ltrim - Strip whitespace (or other characters) from the beginning of a string
    • 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 - Send 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 - Find highest value
    • 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 - Calculate the md5 hash of a string
    • md5_file - Calculates the md5 hash of a given file
    • mdecrypt_generic - Decrypts data
    • Memcache::add - Add an item to the server
    • Memcache::addServer - Add a memcached server to connection pool
    • Memcache::close - Close memcached server connection
    • Memcache::connect - Open memcached server connection
    • Memcache::decrement - Decrement item's value
    • Memcache::delete - Delete item from the server
    • Memcache::flush - Flush all existing items at the server
    • Memcache::get - Retrieve item from the server
    • Memcache::getExtendedStats - Get statistics from all servers in pool
    • Memcache::getServerStatus - Returns server status
    • Memcache::getStats - Get statistics of the server
    • Memcache::getVersion - Return version of the server
    • Memcache::increment - Increment item's value
    • Memcache::pconnect - Open memcached server persistent connection
    • Memcache::replace - Replace value of the existing item
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - Enable automatic compression of large values
    • Memcache::setServerParams - Changes server parameters and status at runtime
    • Memcached::add - 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 - Calculate the metaphone key of a string
    • method_exists - Checks if the class method exists
    • mhash - Computes hash
    • mhash_count - Gets the highest available hash ID
    • mhash_get_block_size - Gets the block size of the specified hash
    • mhash_get_hash_name - Gets the name of the specified hash
    • mhash_keygen_s2k - Generates a key
    • microtime - Return current Unix timestamp with microseconds
    • mime_content_type - Detect MIME Content-type for a file
    • min - Find lowest value
    • mkdir - Makes directory
    • mktime - Get Unix timestamp for a date
    • money_format - Formats a number as a currency string
    • 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 - Moves an uploaded file to a new location
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC)
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • mt_getrandmax - Show largest possible random value
    • mt_rand - Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand - Seeds the Mersenne Twister Random Number Generator
    • MultipleIterator::attachIterator - Attaches iterator information
    • MultipleIterator::containsIterator - Checks if an iterator is attached
    • MultipleIterator::countIterators - Gets the number of attached iterator instances
    • MultipleIterator::current - Gets the registered iterator instances
    • MultipleIterator::detachIterator - Detaches an iterator
    • MultipleIterator::getFlags - Gets the flag information
    • MultipleIterator::key - Gets the registered iterator instances
    • MultipleIterator::next - Moves all attached iterator instances forward
    • MultipleIterator::rewind - Rewinds all attached iterator instances
    • MultipleIterator::setFlags - Sets flags
    • MultipleIterator::valid - Checks the validity of sub iterators
    • MultipleIterator::__construct - Constructs a new MultipleIterator
    • mysqli::$affected_rows - Gets the number of affected rows in a previous MySQL operation
    • mysqli::$client_info - Get MySQL client info
    • mysqli::$client_version - Returns the MySQL client version as an integer
    • mysqli::$connect_errno - Returns the error code from last connect call
    • mysqli::$connect_error - Returns a description of the last connection error
    • mysqli::$errno - Returns the error code for the most recent function call
    • mysqli::$error - Returns a string description of the last error
    • mysqli::$error_list - Returns a list of errors from the last command executed
    • mysqli::$field_count - Returns the number of columns for the most recent query
    • mysqli::$host_info - Returns a string representing the type of connection used
    • mysqli::$info - Retrieves information about the most recently executed query
    • mysqli::$insert_id - Returns the value generated for an AUTO_INCREMENT column by the last query
    • mysqli::$protocol_version - Returns the version of the MySQL protocol used
    • mysqli::$server_info - Returns the version of the MySQL server
    • mysqli::$server_version - Returns the version of the MySQL server as an integer
    • mysqli::$sqlstate - Returns the SQLSTATE error from previous MySQL operation
    • mysqli::$thread_id - Returns the thread ID for the current connection
    • mysqli::$warning_count - Returns the number of warnings from the last query for the given link
    • mysqli::autocommit - Turns on or off auto-committing database modifications
    • mysqli::begin_transaction - Starts a transaction
    • mysqli::change_user - Changes the user of the specified database connection
    • mysqli::character_set_name - Returns the current character set of the database connection
    • mysqli::close - Closes a previously opened database connection
    • mysqli::commit - Commits the current transaction
    • mysqli::debug - Performs debugging operations
    • mysqli::dump_debug_info - Dump debugging information into the log
    • mysqli::escape_string - Alias of mysqli_real_escape_string
    • mysqli::execute_query - Prepares, binds parameters, and executes SQL statement
    • mysqli::get_charset - Returns a character set object
    • mysqli::get_connection_stats - Returns statistics about the client connection
    • mysqli::get_warnings - Get result of SHOW WARNINGS
    • mysqli::init - Initializes MySQLi and returns an object for use with mysqli_real_connect()
    • mysqli::kill - Asks the server to kill a MySQL thread
    • mysqli::more_results - Check if there are any more query results from a multi query
    • mysqli::multi_query - Performs one or more queries on the database
    • mysqli::next_result - Prepare next result from multi_query
    • mysqli::options - Set options
    • mysqli::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll - Poll connections
    • mysqli::prepare - Prepares an SQL statement for execution
    • mysqli::query - Performs a query on the database
    • mysqli::real_connect - Opens a connection to a mysql server
    • mysqli::real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • mysqli::real_query - Execute an SQL query
    • mysqli::reap_async_query - Get result from async query
    • mysqli::refresh - Refreshes
    • mysqli::release_savepoint - Removes the named savepoint from the set of savepoints of the current transaction
    • mysqli::rollback - Rolls back current transaction
    • mysqli::savepoint - Set a named transaction savepoint
    • mysqli::select_db - Selects the default database for database queries
    • mysqli::set_charset - Sets the client character set
    • mysqli::set_opt - Alias of mysqli_options
    • mysqli::ssl_set - Used for establishing secure connections using SSL
    • mysqli::stat - Gets the current system status
    • mysqli::stmt_init - Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • mysqli::store_result - Transfers a result set from the last query
    • mysqli::thread_safe - Returns whether thread safety is given or not
    • mysqli::use_result - Initiate a result set retrieval
    • mysqli::__construct - Open a new connection to the MySQL server
    • mysqli_connect - Alias of mysqli::__construct
    • mysqli_driver::$report_mode - Sets mysqli error reporting mode
    • mysqli_driver::embedded_server_end - Stop embedded server
    • mysqli_driver::embedded_server_start - Initialize and start embedded server
    • mysqli_execute - Alias of mysqli_stmt_execute
    • mysqli_get_client_stats - Returns client per-process statistics
    • mysqli_get_links_stats - Return information about open and cached links
    • mysqli_report - Alias of mysqli_driver->report_mode
    • mysqli_result::$current_field - Get current field offset of a result pointer
    • mysqli_result::$field_count - Gets the number of fields in the result set
    • mysqli_result::$lengths - Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows - Gets the number of rows in the result set
    • mysqli_result::data_seek - Adjusts the result pointer to an arbitrary row in the result
    • mysqli_result::fetch_all - Fetch all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array - Fetch the next row of a result set as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc - Fetch the next row of a result set as an associative array
    • mysqli_result::fetch_column - Fetch a single column from the next row of a result set
    • mysqli_result::fetch_field - Returns the next field in the result set
    • mysqli_result::fetch_fields - Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_field_direct - Fetch meta-data for a single field
    • mysqli_result::fetch_object - Fetch the next row of a result set as an object
    • mysqli_result::fetch_row - Fetch the next row of a result set as an enumerated array
    • mysqli_result::field_seek - Set result pointer to a specified field offset
    • mysqli_result::free - Frees the memory associated with a result
    • mysqli_result::getIterator - Retrieve an external iterator
    • mysqli_result::__construct - Constructs a mysqli_result object
    • mysqli_sql_exception::getSqlState - Returns the SQLSTATE error code
    • mysqli_stmt::$affected_rows - Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
    • mysqli_stmt::$errno - Returns the error code for the most recent statement call
    • mysqli_stmt::$error - Returns a string description for last statement error
    • mysqli_stmt::$error_list - Returns a list of errors from the last statement executed
    • mysqli_stmt::$field_count - Returns the number of columns in the given statement
    • mysqli_stmt::$insert_id - Get the ID generated from the previous INSERT operation
    • mysqli_stmt::$num_rows - Returns the number of rows fetched from the server
    • mysqli_stmt::$param_count - Returns the number of parameters for the given statement
    • mysqli_stmt::$sqlstate - Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::attr_get - Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set - Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param - Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result - Binds variables to a prepared statement for result storage
    • mysqli_stmt::close - Closes a prepared statement
    • mysqli_stmt::data_seek - Adjusts the result pointer to an arbitrary row in the buffered result
    • mysqli_stmt::execute - Executes a prepared statement
    • mysqli_stmt::fetch - Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::free_result - Frees stored result memory for the given statement handle
    • mysqli_stmt::get_result - Gets a result set from a prepared statement as a mysqli_result object
    • mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
    • mysqli_stmt::more_results - Check if there are more query results from a multiple query
    • mysqli_stmt::next_result - Reads the next result from a multiple query
    • mysqli_stmt::prepare - Prepares an SQL statement for execution
    • mysqli_stmt::reset - Resets a prepared statement
    • mysqli_stmt::result_metadata - Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data - Send data in blocks
    • mysqli_stmt::store_result - Stores a result set in an internal buffer
    • mysqli_stmt::__construct - Constructs a new mysqli_stmt object
    • mysqli_warning::next - Fetch next warning
    • mysqli_warning::__construct - Private constructor to disallow direct instantiation
    • mysql_affected_rows - Get number of affected rows in previous MySQL operation
    • mysql_client_encoding - Returns the name of the character set
    • mysql_close - Close MySQL connection
    • mysql_connect - Open a connection to a MySQL Server
    • mysql_create_db - Create a MySQL database
    • mysql_data_seek - Move internal result pointer
    • mysql_db_name - Retrieves database name from the call to mysql_list_dbs
    • mysql_db_query - Selects a database and executes a query on it
    • mysql_drop_db - Drop (delete) a MySQL database
    • mysql_errno - Returns the numerical value of the error message from previous MySQL operation
    • mysql_error - Returns the text of the error message from previous MySQL operation
    • mysql_escape_string - Escapes a string for use in a mysql_query
    • mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mysql_fetch_assoc - Fetch a result row as an associative array
    • mysql_fetch_field - Get column information from a result and return as an object
    • mysql_fetch_lengths - Get the length of each output in a result
    • mysql_fetch_object - Fetch a result row as an object
    • mysql_fetch_row - Get a result row as an enumerated array
    • mysql_field_flags - Get the flags associated with the specified field in a result
    • mysql_field_len - Returns the length of the specified field
    • mysql_field_name - Get the name of the specified field in a result
    • mysql_field_seek - Set result pointer to a specified field offset
    • mysql_field_table - Get name of the table the specified field is in
    • mysql_field_type - Get the type of the specified field in a result
    • mysql_free_result - Free result memory
    • mysql_get_client_info - Get MySQL client info
    • mysql_get_host_info - Get MySQL host info
    • mysql_get_proto_info - Get MySQL protocol info
    • mysql_get_server_info - Get MySQL server info
    • mysql_info - Get information about the most recent query
    • mysql_insert_id - Get the ID generated in the last query
    • mysql_list_dbs - List databases available on a MySQL server
    • mysql_list_fields - List MySQL table fields
    • mysql_list_processes - List MySQL processes
    • mysql_list_tables - List tables in a MySQL database
    • mysql_num_fields - Get number of fields in result
    • mysql_num_rows - Get number of rows in result
    • mysql_pconnect - Open a persistent connection to a MySQL server
    • mysql_ping - Ping a server connection or reconnect if there is no connection
    • mysql_query - Send a MySQL query
    • mysql_real_escape_string - Escapes special characters in a string for use in an SQL statement
    • mysql_result - Get result data
    • mysql_select_db - Select a MySQL database
    • mysql_set_charset - Sets the client character set
    • mysql_stat - Get current system status
    • mysql_tablename - Get table name of field
    • mysql_thread_id - Return the current thread ID
    • mysql_unbuffered_query - Send an SQL query to MySQL without fetching and buffering the result rows
    • mysql_xdevapi\Client::close - Close client
  • n
    • natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • natsort - Sort an array using a "natural order" algorithm
    • net_get_interfaces - Get network interfaces
    • next - Advance the internal pointer of an array
    • ngettext - Plural version of gettext
    • nl2br - Inserts HTML line breaks before all newlines in a string
    • nl_langinfo - Query language and locale information
    • NoRewindIterator::current - Get the current value
    • NoRewindIterator::key - Get the current key
    • NoRewindIterator::next - Forward to the next element
    • NoRewindIterator::rewind - Prevents the rewind operation on the inner iterator
    • NoRewindIterator::valid - Validates the iterator
    • NoRewindIterator::__construct - Construct a NoRewindIterator
    • Normalizer::getRawDecomposition - Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized - 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 - Format a number with grouped thousands
  • o
    • OAuth::disableDebug - Turn off verbose debugging
    • OAuth::disableRedirects - Turn off redirects
    • OAuth::disableSSLChecks - Turn off SSL checks
    • OAuth::enableDebug - Turn on verbose debugging
    • OAuth::enableRedirects - Turn on redirects
    • OAuth::enableSSLChecks - Turn on SSL checks
    • OAuth::fetch - Fetch an OAuth protected resource
    • OAuth::generateSignature - Generate a signature
    • OAuth::getAccessToken - Fetch an access token
    • OAuth::getCAPath - Gets CA information
    • OAuth::getLastResponse - Get the last response
    • OAuth::getLastResponseHeaders - Get headers for last response
    • OAuth::getLastResponseInfo - Get HTTP information about the last response
    • OAuth::getRequestHeader - Generate OAuth header string signature
    • OAuth::getRequestToken - Fetch a request token
    • OAuth::setAuthType - Set authorization type
    • OAuth::setCAPath - Set CA path and info
    • OAuth::setNonce - Set the nonce for subsequent requests
    • OAuth::setRequestEngine - The setRequestEngine purpose
    • OAuth::setRSACertificate - Set the RSA certificate
    • OAuth::setSSLChecks - Tweak specific SSL checks for requests
    • OAuth::setTimestamp - Set the timestamp
    • OAuth::setToken - Sets the token and secret
    • OAuth::setVersion - Set the OAuth version
    • OAuth::__construct - Create a new OAuth object
    • OAuth::__destruct - The destructor
    • OAuthProvider::addRequiredParameter - Add required parameters
    • OAuthProvider::callconsumerHandler - Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler - Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler - Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest - Check an oauth request
    • OAuthProvider::consumerHandler - Set the consumerHandler handler callback
    • OAuthProvider::generateToken - Generate a random token
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remove a required parameter
    • OAuthProvider::reportProblem - Report a problem
    • OAuthProvider::setParam - Set a parameter
    • OAuthProvider::setRequestTokenPath - Set request token path
    • OAuthProvider::timestampNonceHandler - Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler - Set the tokenHandler handler callback
    • OAuthProvider::__construct - Constructs a new OAuthProvider object
    • oauth_get_sbs - Generate a Signature Base String
    • oauth_urlencode - Encode a URI to RFC 3986
    • ob_clean - Clean (erase) the output buffer
    • ob_end_clean - Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush - Flush (send) the output buffer and turn off output buffering
    • ob_flush - Flush (send) the output buffer
    • ob_get_clean - Get current buffer contents and delete current output buffer
    • ob_get_contents - Return the contents of the output buffer
    • ob_get_flush - Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length - Return the length of the output buffer
    • ob_get_level - Return the nesting level of the output buffering mechanism
    • ob_get_status - Get status of output buffers
    • ob_gzhandler - ob_start callback function to gzip output buffer
    • ob_iconv_handler - Convert character encoding as output buffer handler
    • ob_implicit_flush - Turn implicit flush on/off
    • ob_list_handlers - List all output handlers in use
    • ob_start - Turn on output buffering
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • ocibindbyname - Alias of oci_bind_by_name
    • ocicancel - Alias of oci_cancel
    • ocicloselob - Alias of OCILob::close
    • ocicollappend - Alias of OCICollection::append
    • ocicollassign - Alias of OCICollection::assign
    • ocicollassignelem - Alias of OCICollection::assignElem
    • OCICollection::append - Appends element to the collection
    • OCICollection::assign - Assigns a value to the collection from another existing collection
    • OCICollection::assignElem - Assigns a value to the element of the collection
    • OCICollection::free - Frees the resources associated with the collection object
    • OCICollection::getElem - Returns value of the element
    • OCICollection::max - Returns the maximum number of elements in the collection
    • OCICollection::size - Returns size of the collection
    • OCICollection::trim - Trims elements from the end of the collection
    • ocicollgetelem - Alias of OCICollection::getElem
    • ocicollmax - Alias of OCICollection::max
    • ocicollsize - Alias of OCICollection::size
    • ocicolltrim - Alias of OCICollection::trim
    • ocicolumnisnull - Alias of oci_field_is_null
    • ocicolumnname - Alias of oci_field_name
    • ocicolumnprecision - Alias of oci_field_precision
    • ocicolumnscale - Alias of oci_field_scale
    • ocicolumnsize - Alias of oci_field_size
    • ocicolumntype - Alias of oci_field_type
    • ocicolumntyperaw - Alias of oci_field_type_raw
    • ocicommit - Alias of oci_commit
    • ocidefinebyname - Alias of oci_define_by_name
    • ocierror - Alias of oci_error
    • ociexecute - Alias of oci_execute
    • ocifetch - Alias of oci_fetch
    • ocifetchinto - Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
    • ocifetchstatement - Alias of oci_fetch_all
    • ocifreecollection - Alias of OCICollection::free
    • ocifreecursor - Alias of oci_free_statement
    • ocifreedesc - Alias of OCILob::free
    • ocifreestatement - Alias of oci_free_statement
    • ociinternaldebug - Alias of oci_internal_debug
    • ociloadlob - Alias of 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 of 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 of OCILob::export
    • ocilogoff - Alias of oci_close
    • ocilogon - Alias of oci_connect
    • ocinewcollection - Alias of oci_new_collection
    • ocinewcursor - Alias of oci_new_cursor
    • ocinewdescriptor - Alias of oci_new_descriptor
    • ocinlogon - Alias of oci_new_connect
    • ocinumcols - Alias of oci_num_fields
    • ociparse - Alias of oci_parse
    • ociplogon - Alias of oci_pconnect
    • ociresult - Alias of oci_result
    • ocirollback - Alias of oci_rollback
    • ocirowcount - Alias of oci_num_rows
    • ocisavelob - Alias of OCILob::save
    • ocisavelobfile - Alias of OCILob::import
    • ociserverversion - Alias of oci_server_version
    • ocisetprefetch - Alias of oci_set_prefetch
    • ocistatementtype - Alias of oci_statement_type
    • ociwritelobtofile - Alias of OCILob::export
    • ociwritetemporarylob - Alias of OCILob::writeTemporary
    • oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
    • oci_cancel - Cancels reading from cursor
    • oci_client_version - Returns the Oracle client library version
    • oci_close - Closes an Oracle connection
    • oci_commit - Commits the outstanding database transaction
    • oci_connect - Connect to an Oracle database
    • oci_define_by_name - Associates a PHP variable with a column for query fetches
    • oci_error - Returns the last error found
    • oci_execute - Executes a statement
    • oci_fetch - Fetches the next row from a query into internal buffers
    • oci_fetch_all - Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array - Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc - Returns the next row from a query as an associative array
    • oci_fetch_object - Returns the next row from a query as an object
    • oci_fetch_row - Returns the next row from a query as a numeric array
    • oci_field_is_null - Checks if a field in the currently fetched row is null
    • oci_field_name - Returns the name of a field from the statement
    • oci_field_precision - Tell the precision of a field
    • oci_field_scale - Tell the scale of the field
    • oci_field_size - Returns field's size
    • oci_field_type - Returns a field's data type name
    • oci_field_type_raw - Tell the raw Oracle data type of the field
    • oci_free_descriptor - Frees a descriptor
    • oci_free_statement - Frees all resources associated with statement or cursor
    • oci_get_implicit_resultset - Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copies large object
    • oci_lob_is_equal - Compares two LOB/FILE locators for equality
    • oci_new_collection - Allocates new collection object
    • oci_new_connect - Connect to the Oracle server using a unique connection
    • oci_new_cursor - Allocates and returns a new cursor (statement handle)
    • oci_new_descriptor - Initializes a new empty LOB or FILE descriptor
    • oci_num_fields - Returns the number of result columns in a statement
    • oci_num_rows - Returns number of rows affected during statement execution
    • oci_parse - Prepares an Oracle statement for execution
    • oci_password_change - Changes password of Oracle's user
    • oci_pconnect - Connect to an Oracle database using a persistent connection
    • oci_register_taf_callback - Register a user-defined callback function for Oracle Database TAF
    • oci_result - Returns field's value from the fetched row
    • oci_rollback - Rolls back the outstanding database transaction
    • oci_server_version - Returns the Oracle Database version
    • oci_set_action - Sets the action name
    • oci_set_call_timeout - Sets a millisecond timeout for database calls
    • oci_set_client_identifier - Sets the client identifier
    • oci_set_client_info - Sets the client information
    • oci_set_db_operation - Sets the database operation
    • oci_set_edition - Sets the database edition
    • oci_set_module_name - Sets the module name
    • oci_set_prefetch - Sets number of rows to be prefetched by queries
    • oci_set_prefetch_lob - Sets the amount of data prefetched for each CLOB or BLOB.
    • oci_statement_type - Returns the type of a statement
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - Octal to decimal
    • odbc_autocommit - Toggle autocommit behaviour
    • odbc_binmode - Handling of binary column data
    • odbc_close - Close an ODBC connection
    • odbc_close_all - Close all ODBC connections
    • odbc_columnprivileges - Lists columns and associated privileges for the given table
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Commit an ODBC transaction
    • odbc_connect - Connect to a datasource
    • odbc_connection_string_is_quoted - Determines if an ODBC connection string value is quoted
    • odbc_connection_string_quote - Quotes an ODBC connection string value
    • odbc_connection_string_should_quote - Determines if an ODBC connection string value should be quoted
    • odbc_cursor - Get cursorname
    • odbc_data_source - Returns information about available DSNs
    • odbc_do - Alias of odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Directly execute an SQL statement
    • odbc_execute - Execute a prepared statement
    • odbc_fetch_array - Fetch a result row as an associative array
    • odbc_fetch_into - Fetch one result row into array
    • odbc_fetch_object - Fetch a result row as an object
    • odbc_fetch_row - Fetch a row
    • odbc_field_len - Get the length (precision) of a field
    • odbc_field_name - Get the columnname
    • odbc_field_num - Return column number
    • odbc_field_precision - Alias of odbc_field_len
    • odbc_field_scale - Get the scale of a field
    • odbc_field_type - Datatype of a field
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Free resources associated with a result
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Handling of LONG columns
    • odbc_next_result - Checks if multiple results are available
    • odbc_num_fields - Number of columns in a result
    • odbc_num_rows - Number of rows in a result
    • odbc_pconnect - Open a persistent database connection
    • odbc_prepare - Prepares a statement for execution
    • odbc_primarykeys - Gets the primary keys for a table
    • odbc_procedurecolumns - Retrieve information about parameters to procedures
    • odbc_procedures - Get the list of procedures stored in a specific data source
    • odbc_result - Get result data
    • odbc_result_all - Print result as HTML table
    • odbc_rollback - Rollback a transaction
    • odbc_setoption - Adjust ODBC settings
    • odbc_specialcolumns - Retrieves special columns
    • odbc_statistics - Retrieve statistics about a table
    • odbc_tableprivileges - Lists tables and the privileges associated with each table
    • odbc_tables - Get the list of table names stored in a specific data source
    • ogg:// - 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 - Get status information about the cache
    • opcache_invalidate - Invalidates a cached script
    • opcache_is_script_cached - Tells whether a script is cached in OPCache
    • opcache_reset - Resets the contents of the opcode cache
    • 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 - Open directory handle
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - Gets the cipher iv length
    • openssl_cipher_key_length - Gets the cipher key length
    • openssl_cms_decrypt - Decrypt a CMS message
    • openssl_cms_encrypt - Encrypt a CMS message
    • openssl_cms_read - Export the CMS file to an array of PEM certificates
    • openssl_cms_sign - Sign a file
    • openssl_cms_verify - Verify a CMS signature
    • openssl_csr_export - Exports a CSR as a string
    • openssl_csr_export_to_file - Exports a CSR to a file
    • openssl_csr_get_public_key - Returns the public key of a CSR
    • openssl_csr_get_subject - Returns the subject of a CSR
    • openssl_csr_new - Generates a CSR
    • openssl_csr_sign - Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt - Decrypts data
    • openssl_dh_compute_key - Computes shared secret for public value of remote DH public key and local DH key
    • openssl_digest - Computes a digest
    • openssl_encrypt - Encrypts data
    • openssl_error_string - Return openSSL error message
    • openssl_free_key - Free key resource
    • openssl_get_cert_locations - Retrieve the available certificate locations
    • openssl_get_cipher_methods - Gets available cipher methods
    • openssl_get_curve_names - Gets list of available curve names for ECC
    • openssl_get_md_methods - Gets available digest methods
    • openssl_get_privatekey - Alias of openssl_pkey_get_private
    • openssl_get_publickey - Alias of openssl_pkey_get_public
    • openssl_open - Open sealed data
    • openssl_pbkdf2 - Generates a PKCS5 v2 PBKDF2 string
    • openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt - Encrypt an S/MIME message
    • openssl_pkcs7_read - Export the PKCS7 file to an array of PEM certificates
    • openssl_pkcs7_sign - Sign an S/MIME message
    • openssl_pkcs7_verify - Verifies the signature of an S/MIME signed message
    • openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store File to variable
    • openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - Gets an exportable representation of a key into a string
    • openssl_pkey_export_to_file - Gets an exportable representation of a key into a file
    • openssl_pkey_free - Frees a private key
    • openssl_pkey_get_details - Returns an array with the key details
    • openssl_pkey_get_private - Get a private key
    • openssl_pkey_get_public - Extract public key from certificate and prepare it for use
    • openssl_pkey_new - Generates a new private key
    • openssl_private_decrypt - Decrypts data with private key
    • openssl_private_encrypt - Encrypts data with private key
    • openssl_public_decrypt - Decrypts data with public key
    • openssl_public_encrypt - Encrypts data with public key
    • openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
    • openssl_seal - Seal (encrypt) data
    • openssl_sign - Generate signature
    • openssl_spki_export - Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_export_challenge - Exports the challenge associated with a signed public key and challenge
    • openssl_spki_new - Generate a new signed public key and challenge
    • openssl_spki_verify - Verifies a signed public key and challenge
    • openssl_verify - Verify signature
    • openssl_x509_checkpurpose - Verifies if a certificate can be used for a particular purpose
    • openssl_x509_check_private_key - Checks if a private key corresponds to a certificate
    • openssl_x509_export - Exports a certificate as a string
    • openssl_x509_export_to_file - Exports a certificate to file
    • openssl_x509_fingerprint - Calculates the fingerprint, or digest, of a given X.509 certificate
    • openssl_x509_free - Free certificate resource
    • openssl_x509_parse - Parse an X509 certificate and return the information as an array
    • openssl_x509_read - Parse an X.509 certificate and return an object for it
    • openssl_x509_verify - Verifies digital signature of x509 certificate against a public key
    • ord - Convert the first byte of a string to a value between 0 and 255
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry
    • output_add_rewrite_var - Add URL rewriter values
    • output_reset_rewrite_vars - Reset URL rewriter values
  • p
    • pack - Pack data into binary string
    • 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 - Parse a configuration file
    • parse_ini_string - Parse a configuration string
    • parse_str - Parses the string into variables
    • parse_url - Parse a URL and return its components
    • passthru - Execute an external program and display raw output
    • password_algos - Get available password hashing algorithm IDs
    • password_get_info - Returns information about the given hash
    • password_hash - Creates a password hash
    • password_needs_rehash - Checks if the given hash matches the given options
    • password_verify - Verifies that a password matches a hash
    • pathinfo - Returns information about a file path
    • pclose - Closes process file pointer
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - Alias of pcntl_get_last_error
    • pcntl_exec - Executes specified program in current process space
    • pcntl_fork - Forks the currently running process
    • pcntl_getpriority - Get the priority of any process
    • pcntl_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_rfork - Manipulates process resources
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_signal_get_handler - Get the current handler for specified signal
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_strerror - Retrieve the system error message associated with the given errno
    • pcntl_unshare - Dissociates parts of the process execution context
    • pcntl_wait - Waits on or returns the status of a forked child
    • pcntl_waitpid - Waits on or returns the status of a forked child
    • pcntl_wexitstatus - Returns the return code of a terminated child
    • pcntl_wifexited - Checks if status code represents a normal exit
    • pcntl_wifsignaled - Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped - Checks whether the child process is currently stopped
    • pcntl_wstopsig - Returns the signal which caused the child to stop
    • pcntl_wtermsig - Returns the signal which caused the child to terminate
    • PDO::beginTransaction - Initiates a transaction
    • PDO::commit - Commits a transaction
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo - Fetch extended error information associated with the last operation on the database handle
    • PDO::exec - Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute - Retrieve a database connection attribute
    • PDO::getAvailableDrivers - Return an array of available PDO drivers
    • PDO::inTransaction - Checks if inside a transaction
    • PDO::lastInsertId - Returns the ID of the last inserted row or sequence value
    • PDO::pgsqlCopyFromArray - Copy data from PHP array into table
    • PDO::pgsqlCopyFromFile - Copy data from file into table
    • PDO::pgsqlCopyToArray - Copy data from database table into PHP array
    • PDO::pgsqlCopyToFile - Copy data from table into file
    • PDO::pgsqlGetNotify - Get asynchronous notification
    • PDO::pgsqlGetPid - Get the server PID
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - Prepares a statement for execution and returns a statement object
    • PDO::query - Prepares and executes an SQL statement without placeholders
    • PDO::quote - Quotes a string for use in a query
    • PDO::rollBack - Rolls back a transaction
    • PDO::setAttribute - Set an attribute
    • PDO::sqliteCreateAggregate - Registers an aggregating User Defined Function for use in SQL statements
    • PDO::sqliteCreateCollation - Registers a User Defined Function for use as a collating function in SQL statements
    • PDO::sqliteCreateFunction - Registers a User Defined Function for use in SQL statements
    • PDO::__construct - Creates a PDO instance representing a connection to a database
    • PDOStatement::bindColumn - Bind a column to a PHP variable
    • PDOStatement::bindParam - Binds a parameter to the specified variable name
    • PDOStatement::bindValue - Binds a value to a parameter
    • PDOStatement::closeCursor - Closes the cursor, enabling the statement to be executed again
    • PDOStatement::columnCount - Returns the number of columns in the result set
    • PDOStatement::debugDumpParams - Dump an SQL prepared command
    • PDOStatement::errorCode - Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement::errorInfo - Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement::execute - Executes a prepared statement
    • PDOStatement::fetch - Fetches the next row from a result set
    • PDOStatement::fetchAll - Fetches the remaining rows from a result set
    • PDOStatement::fetchColumn - Returns a single column from the next row of a result set
    • PDOStatement::fetchObject - Fetches the next row and returns it as an object
    • PDOStatement::getAttribute - Retrieve a statement attribute
    • PDOStatement::getColumnMeta - Returns metadata for a column in a result set
    • PDOStatement::getIterator - Gets result set iterator
    • PDOStatement::nextRowset - Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
    • PDOStatement::setAttribute - Set a statement attribute
    • PDOStatement::setFetchMode - Set the default fetch mode for this statement
    • 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 - Connecting to MySQL databases
    • 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 - Connecting to SQLite databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Open persistent Internet or Unix domain socket connection
    • pg_affected_rows - Returns number of affected records (tuples)
    • pg_cancel_query - Cancel an asynchronous query
    • pg_client_encoding - Gets the client encoding
    • pg_close - Closes a PostgreSQL connection
    • pg_connect - Open a PostgreSQL connection
    • pg_connection_busy - Get connection is busy or not
    • pg_connection_reset - Reset connection (reconnect)
    • pg_connection_status - Get connection status
    • pg_connect_poll - Poll the status of an in-progress asynchronous PostgreSQL connection attempt
    • pg_consume_input - Reads input on the connection
    • pg_convert - Convert associative array values into forms suitable for SQL statements
    • pg_copy_from - Insert records into a table from an array
    • pg_copy_to - Copy a table to an array
    • pg_dbname - Get the database name
    • pg_delete - Deletes records
    • pg_end_copy - Sync with PostgreSQL backend
    • pg_escape_bytea - Escape a string for insertion into a bytea field
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - Escape a string for query
    • pg_execute - Sends a request to execute a prepared statement with given parameters, and waits for the result
    • pg_fetch_all - Fetches all rows from a result as an array
    • pg_fetch_all_columns - Fetches all rows in a particular result column as an array
    • pg_fetch_array - Fetch a row as an array
    • pg_fetch_assoc - Fetch a row as an associative array
    • pg_fetch_object - Fetch a row as an object
    • pg_fetch_result - Returns values from a result instance
    • pg_fetch_row - Get a row as an enumerated array
    • pg_field_is_null - Test if a field is SQL NULL
    • pg_field_name - Returns the name of a field
    • pg_field_num - Returns the field number of the named field
    • pg_field_prtlen - Returns the printed length
    • pg_field_size - Returns the internal storage size of the named field
    • pg_field_table - Returns the name or oid of the tables field
    • pg_field_type - Returns the type name for the corresponding field number
    • pg_field_type_oid - Returns the type ID (OID) for the corresponding field number
    • pg_flush - Flush outbound query data on the connection
    • pg_free_result - Free result memory
    • pg_get_notify - Gets SQL NOTIFY message
    • pg_get_pid - Gets the backend's process ID
    • pg_get_result - Get asynchronous query result
    • pg_host - Returns the host name associated with the connection
    • pg_insert - Insert array into table
    • pg_last_error - Get the last error message string of a connection
    • pg_last_notice - Returns the last notice message from PostgreSQL server
    • pg_last_oid - Returns the last row's OID
    • pg_lo_close - Close a large object
    • pg_lo_create - Create a large object
    • pg_lo_export - Export a large object to file
    • pg_lo_import - Import a large object from file
    • pg_lo_open - Open a large object
    • pg_lo_read - Read a large object
    • pg_lo_read_all - Reads an entire large object and send straight to browser
    • pg_lo_seek - Seeks position within a large object
    • pg_lo_tell - Returns current seek position a of large object
    • pg_lo_truncate - Truncates a large object
    • pg_lo_unlink - Delete a large object
    • pg_lo_write - Write to a large object
    • pg_meta_data - Get meta data for table
    • pg_num_fields - Returns the number of fields in a result
    • pg_num_rows - Returns the number of rows in a result
    • pg_options - Get the options associated with the connection
    • pg_parameter_status - Looks up a current parameter setting of the server
    • pg_pconnect - Open a persistent PostgreSQL connection
    • pg_ping - Ping database connection
    • pg_port - Return the port number associated with the connection
    • pg_prepare - Submits a request to create a prepared statement with the given parameters, and waits for completion
    • pg_put_line - Send a NULL-terminated string to PostgreSQL backend
    • pg_query - Execute a query
    • pg_query_params - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
    • pg_result_error - Get error message associated with result
    • pg_result_error_field - Returns an individual field of an error report
    • pg_result_seek - Set internal row offset in result instance
    • pg_result_status - Get status of query result
    • pg_select - Select records
    • pg_send_execute - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
    • pg_send_prepare - Sends a request to create a prepared statement with the given parameters, without waiting for completion
    • pg_send_query - Sends asynchronous query
    • pg_send_query_params - Submits a command and separate parameters to the server without waiting for the result(s)
    • pg_set_client_encoding - Set the client encoding
    • pg_set_error_context_visibility - Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
    • pg_set_error_verbosity - Determines the verbosity of messages returned by pg_last_error and pg_result_error
    • pg_socket - Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace - Enable tracing a PostgreSQL connection
    • pg_transaction_status - Returns the current in-transaction status of the server
    • pg_tty - Return the TTY name associated with the connection
    • pg_unescape_bytea - Unescape binary for bytea type
    • pg_untrace - Disable tracing of a PostgreSQL connection
    • pg_update - Update table
    • pg_version - Returns an array with client, protocol and server version (when available)
    • phar:// - 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
    • Phar context options - Phar context option listing
    • PharData::addEmptyDir - Add an empty directory to the tar/zip archive
    • PharData::addFile - Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString - Add a file from a string to the tar/zip archive
    • PharData::buildFromDirectory - Construct a tar/zip archive from the files within a directory
    • PharData::buildFromIterator - Construct a tar or zip archive from an iterator
    • PharData::compress - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles - Compresses all files in the current tar/zip archive
    • PharData::convertToData - Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable - Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy - Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • PharData::extractTo - Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable - Returns true if the tar/zip archive can be modified
    • PharData::offsetSet - Set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset - Remove a file from a tar/zip archive
    • PharData::setAlias - Dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub - Dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setMetadata - Sets phar archive meta-data
    • PharData::setSignatureAlgorithm - Set the signature algorithm for a phar and apply it
    • PharData::setStub - Dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharData::__destruct - Destructs a non-executable tar or zip archive object
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • PharFileInfo::getCompressedSize - Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getContent - Get the complete file contents of the entry
    • PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getMetadata - Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags - Returns the Phar file entry flags
    • PharFileInfo::hasMetadata - Returns the metadata of the entry
    • PharFileInfo::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::__construct - Construct a Phar entry object
    • PharFileInfo::__destruct - Destructs a Phar entry object
    • php:// - 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 - Description
    • phpdbg_exec - Attempts to set the execution context
    • phpdbg_get_executable - Description
    • phpdbg_prompt - Sets the command prompt
    • phpdbg_start_oplog - Description
    • phpinfo - Outputs information about PHP's configuration
    • PhpToken::getTokenName - Returns the name of the token.
    • PhpToken::is - Tells whether the token is of given kind.
    • PhpToken::isIgnorable - Tells whether the token would be ignored by the PHP parser.
    • PhpToken::tokenize - Splits given source into PHP tokens, represented by PhpToken objects.
    • PhpToken::__construct - Returns a new PhpToken object
    • PhpToken::__toString - Returns the textual content of the token.
    • phpversion - Gets the current PHP version
    • php_ini_loaded_file - Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files - Return a list of .ini files parsed from the additional ini dir
    • php_sapi_name - Returns the type of interface between web server and PHP
    • php_strip_whitespace - 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 - Get value of 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 - Opens process file pointer
    • pos - Alias of current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_eaccess - Determine accessibility of a file
    • posix_errno - Alias of posix_get_last_error
    • posix_fpathconf - Returns the value of a configurable limit
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - Return the current process identifier
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_pathconf - Returns the value of a configurable limit
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setrlimit - Set system resource limits
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_sysconf - Returns system runtime information
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - Exponential expression
    • preg_filter - Perform a regular expression search and replace
    • preg_grep - Return array entries that match the pattern
    • preg_last_error - Returns the error code of the last PCRE regex execution
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - Perform a regular expression match
    • preg_match_all - Perform a global regular expression match
    • preg_quote - Quote regular expression characters
    • preg_replace - Perform a regular expression search and replace
    • preg_replace_callback - Perform a regular expression search and replace using a callback
    • preg_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - Split string by a regular expression
    • prev - Rewind the internal array pointer
    • print - Output a string
    • printf - Output a formatted string
    • print_r - Prints human-readable information about a variable
    • proc_close - Close a process opened by proc_open and return the exit code of that process
    • proc_get_status - Get information about a process opened by proc_open
    • proc_nice - Change the priority of the current process
    • proc_open - Execute a command and open file pointers for input/output
    • proc_terminate - Kills a process opened by proc_open
    • property_exists - Checks if the object or class has a property
    • pspell_add_to_personal - Add the word to a personal wordlist
    • pspell_add_to_session - Add the word to the wordlist in the current session
    • pspell_check - Check a word
    • pspell_clear_session - Clear the current session
    • pspell_config_create - Create a config used to open a dictionary
    • pspell_config_data_dir - Location of language data files
    • pspell_config_dict_dir - Location of the main word list
    • pspell_config_ignore - Ignore words less than N characters long
    • pspell_config_mode - Change the mode number of suggestions returned
    • pspell_config_personal - Set a file that contains personal wordlist
    • pspell_config_repl - Set a file that contains replacement pairs
    • pspell_config_runtogether - Consider run-together words as valid compounds
    • pspell_config_save_repl - Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new - Load a new dictionary
    • pspell_new_config - Load a new dictionary with settings based on a given config
    • pspell_new_personal - Load a new dictionary with personal wordlist
    • pspell_save_wordlist - Save the personal wordlist to a file
    • pspell_store_replacement - Store a replacement pair for a word
    • pspell_suggest - Suggest spellings of a word
    • ps_add_bookmark - Add bookmark to current page
    • ps_add_launchlink - Adds link which launches file
    • ps_add_locallink - Adds link to a page in the same document
    • ps_add_note - Adds note to current page
    • ps_add_pdflink - Adds link to a page in a second pdf document
    • ps_add_weblink - Adds link to a web location
    • ps_arc - Draws an arc counterclockwise
    • ps_arcn - Draws an arc clockwise
    • ps_begin_page - Start a new page
    • ps_begin_pattern - Start a new pattern
    • ps_begin_template - Start a new template
    • ps_circle - Draws a circle
    • ps_clip - Clips drawing to current path
    • ps_close - Closes a PostScript document
    • ps_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • ps_continue_text - Continue text in next line
    • ps_curveto - Draws a curve
    • ps_delete - Deletes all resources of a PostScript document
    • ps_end_page - End a page
    • ps_end_pattern - End a pattern
    • ps_end_template - End a template
    • ps_fill - Fills the current path
    • ps_fill_stroke - Fills and strokes the current path
    • ps_findfont - Loads a font
    • ps_get_buffer - Fetches the full buffer containig the generated PS data
    • ps_get_parameter - Gets certain parameters
    • ps_get_value - Gets certain values
    • ps_hyphenate - Hyphenates a word
    • ps_include_file - Reads an external file with raw PostScript code
    • ps_lineto - Draws a line
    • ps_makespotcolor - Create spot color
    • ps_moveto - Sets current point
    • ps_new - Creates a new PostScript document object
    • ps_open_file - Opens a file for output
    • ps_open_image - Reads an image for later placement
    • ps_open_image_file - Opens image from file
    • ps_open_memory_image - Takes an GD image and returns an image for placement in a PS document
    • ps_place_image - Places image on the page
    • ps_rect - Draws a rectangle
    • ps_restore - Restore previously save context
    • ps_rotate - Sets rotation factor
    • ps_save - Save current context
    • ps_scale - Sets scaling factor
    • ps_setcolor - Sets current color
    • ps_setdash - Sets appearance of a dashed line
    • ps_setflat - Sets flatness
    • ps_setfont - Sets font to use for following output
    • ps_setgray - Sets gray value
    • ps_setlinecap - Sets appearance of line ends
    • ps_setlinejoin - Sets how contected lines are joined
    • ps_setlinewidth - Sets width of a line
    • ps_setmiterlimit - Sets the miter limit
    • ps_setoverprintmode - Sets overprint mode
    • ps_setpolydash - Sets appearance of a dashed line
    • ps_set_border_color - Sets color of border for annotations
    • ps_set_border_dash - Sets length of dashes for border of annotations
    • ps_set_border_style - Sets border style of annotations
    • ps_set_info - Sets information fields of document
    • ps_set_parameter - Sets certain parameters
    • ps_set_text_pos - Sets position for text output
    • ps_set_value - Sets certain values
    • ps_shading - Creates a shading for later use
    • ps_shading_pattern - Creates a pattern based on a shading
    • ps_shfill - Fills an area with a shading
    • ps_show - Output text
    • ps_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry of a string
    • ps_stroke - Draws the current path
    • ps_symbol - Output a glyph
    • ps_symbol_name - Gets name of a glyph
    • ps_symbol_width - Gets width of a glyph
    • ps_translate - Sets translation
    • putenv - Sets the value of an environment variable
  • 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 - Convert a quoted-printable string to an 8 bit string
    • quoted_printable_encode - Convert a 8 bit string to a quoted-printable string
    • quotemeta - Quote meta characters
  • r
    • rad2deg - Converts the radian number to the equivalent number in degrees
    • radius_acct_open - Creates a Radius handle for accounting
    • radius_add_server - Adds a server
    • radius_auth_open - Creates a Radius handle for authentication
    • radius_close - Frees all ressources
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_tagged_attr_data - Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag - Extracts the tag from a tagged attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_salt_encrypt_attr - Salt-encrypts a value
    • radius_send_request - Sends the request and waits for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Returns an error message
    • rand - Generate a random integer
    • Random\Engine::generate - Generates randomness
    • Random\Engine\Mt19937::generate - Generate 32 bits of randomness
    • Random\Engine\Mt19937::__construct - Constructs a new Mt19937 engine
    • Random\Engine\Mt19937::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Mt19937::__serialize - Serializes the Mt19937 object
    • Random\Engine\Mt19937::__unserialize - Deserializes the data parameter into a Mt19937 object
    • Random\Engine\PcgOneseq128XslRr64::generate - Generate 64 bits of randomness
    • Random\Engine\PcgOneseq128XslRr64::jump - Efficiently move the engine ahead multiple steps
    • Random\Engine\PcgOneseq128XslRr64::__construct - Constructs a new PCG Oneseq 128 XSL RR 64 engine
    • Random\Engine\PcgOneseq128XslRr64::__debugInfo - Returns the internal state of the engine
    • Random\Engine\PcgOneseq128XslRr64::__serialize - Serializes the PcgOneseq128XslRr64 object
    • Random\Engine\PcgOneseq128XslRr64::__unserialize - Deserializes the data parameter into a PcgOneseq128XslRr64 object
    • Random\Engine\Secure::generate - Generate cryptographically secure randomness
    • Random\Engine\Xoshiro256StarStar::generate - Generate 64 bits of randomness
    • Random\Engine\Xoshiro256StarStar::jump - Efficiently move the engine ahead by 2^128 steps
    • Random\Engine\Xoshiro256StarStar::jumpLong - Efficiently move the engine ahead by 2^192 steps
    • Random\Engine\Xoshiro256StarStar::__construct - Constructs a new xoshiro256** engine
    • Random\Engine\Xoshiro256StarStar::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Xoshiro256StarStar::__serialize - Serializes the Xoshiro256StarStar object
    • Random\Engine\Xoshiro256StarStar::__unserialize - Deserializes the data parameter into a Xoshiro256StarStar object
    • Random\Randomizer::getBytes - Get random bytes
    • Random\Randomizer::getBytesFromString - Get random bytes from a source string
    • Random\Randomizer::getFloat - Get a uniformly selected float
    • Random\Randomizer::getInt - Get a uniformly selected integer
    • Random\Randomizer::nextFloat - Get a float from the right-open interval [0.0, 1.0)
    • Random\Randomizer::nextInt - Get a positive integer
    • Random\Randomizer::pickArrayKeys - Select random array keys
    • Random\Randomizer::shuffleArray - Get a permutation of an array
    • Random\Randomizer::shuffleBytes - Get a byte-wise permutation of a string
    • Random\Randomizer::__construct - Constructs a new Randomizer
    • Random\Randomizer::__serialize - Serializes the Randomizer object
    • Random\Randomizer::__unserialize - Deserializes the data parameter into a Randomizer object
    • random_bytes - Get cryptographically secure random bytes
    • random_int - Get a cryptographically secure, uniformly selected integer
    • range - Create an array containing a range of elements
    • 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 - Decode URL-encoded strings
    • rawurlencode - URL-encode according to RFC 3986
    • readdir - Read entry from directory handle
    • readfile - Outputs a file
    • readgzfile - Output a gz-file
    • readline - Reads a line
    • readline_add_history - Adds a line to the history
    • readline_callback_handler_install - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove - Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char - Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history - Clears the history
    • readline_completion_function - Registers a completion function
    • readline_info - Gets/sets various internal readline variables
    • readline_list_history - Lists the history
    • readline_on_new_line - Inform readline that the cursor has moved to a new line
    • readline_read_history - Reads the history
    • readline_redisplay - Redraws the display
    • readline_write_history - Writes the history
    • readlink - Returns the target of a symbolic link
    • read_exif_data - Alias of exif_read_data
    • realpath - Returns canonicalized absolute pathname
    • realpath_cache_get - Get realpath cache entries
    • realpath_cache_size - Get realpath cache size
    • recode - Alias of recode_string
    • recode_file - Recode from file to file according to recode request
    • recode_string - Recode a string according to a recode request
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object
    • RecursiveCachingIterator::getChildren - 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 - Move to next entry
    • 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 of 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 - Register a function for execution on shutdown
    • register_tick_function - Register a function for execution on each tick
    • rename - Renames a file or directory
    • reset - Set the internal pointer of an array to its first 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 - Restores the previous error handler function
    • restore_exception_handler - Restores the previously defined exception handler function
    • restore_include_path - Restores the value of the include_path configuration option
    • Result::getAffectedItemsCount - Get affected row count
    • Result::getAutoIncrementValue - Get autoincremented value
    • Result::getGeneratedIds - Get generated ids
    • Result::getWarnings - Get warnings from last operation
    • Result::getWarningsCount - Get warning count from last operation
    • Result::__construct - Result constructor
    • ReturnTypeWillChange::__construct - Construct a new ReturnTypeWillChange attribute instance
    • rewind - Rewind the position of a file pointer
    • rewinddir - Rewind directory handle
    • rmdir - Removes directory
    • 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 - Rounds a float
    • RowResult::fetchAll - Get all rows from result
    • RowResult::fetchOne - Get row from result
    • RowResult::getColumnNames - Get all column names
    • RowResult::getColumns - Get column metadata
    • RowResult::getColumnsCount - Get column count
    • RowResult::getWarnings - Get warnings from last operation
    • RowResult::getWarningsCount - Get warning count from last operation
    • RowResult::__construct - RowResult constructor
    • rpmaddtag - Add tag retrieved in query
    • rpmdbinfo - Get information from installed RPM
    • rpmdbsearch - Search RPM packages
    • rpmgetsymlink - Get target of a symlink
    • rpminfo - Get information from a RPM file
    • rpmvercmp - RPM version comparison
    • RRDCreator::addArchive - Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource - Adds data source definition for RRD database
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message
    • rrd_fetch - Fetch the data for graph as array
    • rrd_first - Gets the timestamp of the first sample from rrd file
    • rrd_graph - Creates image from a data
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample
    • rrd_lastupdate - Gets information about last updated data
    • rrd_restore - Restores the RRD file from XML dump
    • rrd_tune - Tunes some RRD database file header options
    • rrd_update - Updates the RRD database
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database
    • rsort - Sort an array in descending order
    • rtrim - Strip whitespace (or other characters) from the end of a string
    • runkit7_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine - Redefine an already defined constant
    • runkit7_constant_remove - Remove/Delete an already defined constant
    • runkit7_function_add - Add a new function, similar to create_function
    • runkit7_function_copy - Copy a function to a new function name
    • runkit7_function_redefine - Replace a function definition with a new implementation
    • runkit7_function_remove - Remove a function definition
    • runkit7_function_rename - Change a function's name
    • runkit7_import - Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit7_method_add - Dynamically adds a new method to a given class
    • runkit7_method_copy - Copies a method from class to another
    • runkit7_method_redefine - Dynamically changes the code of the given method
    • runkit7_method_remove - Dynamically removes the given method
    • runkit7_method_rename - Dynamically changes the name of the given method
    • runkit7_object_id - Return the integer object handle for given object
    • runkit7_superglobals - Return numerically indexed array of registered superglobals
    • runkit7_zval_inspect - Returns information about the passed in value with data types, reference counts, etc
  • s
    • sapi_windows_cp_conv - Convert string from one codepage to another
    • sapi_windows_cp_get - Get current codepage
    • sapi_windows_cp_is_utf8 - Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set - Set process codepage
    • sapi_windows_generate_ctrl_event - Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler - Set or remove a CTRL event handler
    • sapi_windows_vt100_support - Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • scandir - List files and directories inside the specified path
    • Schema::createCollection - Add collection to schema
    • Schema::dropCollection - Drop collection from schema
    • Schema::existsInDatabase - Check if exists in database
    • Schema::getCollection - Get collection from schema
    • Schema::getCollectionAsTable - Get collection table object
    • Schema::getCollections - Get all schema collections
    • Schema::getName - Get schema name
    • Schema::getSession - Get schema session
    • Schema::getTable - Get schema table
    • Schema::getTables - Get schema tables
    • Schema::__construct - constructor
    • SchemaObject::getSchema - Get schema object
    • scoutapm_get_calls - Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions - List functions scoutapm will instrument.
    • SeasLog::alert - Record alert log information
    • SeasLog::analyzerCount - Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail - Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream - Manually release stream flow from logger
    • SeasLog::critical - Record critical log information
    • SeasLog::debug - Record debug log information
    • SeasLog::emergency - Record emergency log information
    • SeasLog::error - Record error log information
    • SeasLog::flushBuffer - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
    • SeasLog::getBasePath - Get SeasLog base path.
    • SeasLog::getBuffer - Get the logs buffer in memory as array
    • SeasLog::getBufferEnabled - Determin if buffer enabled
    • SeasLog::getDatetimeFormat - Get SeasLog datetime format style
    • SeasLog::getLastLogger - Get SeasLog last logger path
    • SeasLog::getRequestID - Get SeasLog request_id differentiated requests
    • SeasLog::getRequestVariable - Get SeasLog request variable
    • SeasLog::info - Record info log information
    • SeasLog::log - The Common Record Log Function
    • SeasLog::notice - Record notice log information
    • SeasLog::setBasePath - Set SeasLog base path
    • SeasLog::setDatetimeFormat - Set SeasLog datetime format style
    • SeasLog::setLogger - Set SeasLog logger name
    • SeasLog::setRequestID - Set SeasLog request_id differentiated requests
    • SeasLog::setRequestVariable - Manually set SeasLog request variable
    • SeasLog::warning - Record warning log information
    • SeasLog::__construct - Description
    • SeasLog::__destruct - Description
    • seaslog_get_author - Get SeasLog author.
    • seaslog_get_version - Get SeasLog version.
    • SeekableIterator::seek - Seeks to a position
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • SensitiveParameter::__construct - Construct a new SensitiveParameter attribute instance
    • SensitiveParameterValue::getValue - Returns the sensitive value
    • SensitiveParameterValue::__construct - Constructs a new SensitiveParameterValue object
    • SensitiveParameterValue::__debugInfo - Protects the sensitive value against accidental exposure
    • Serializable::serialize - String representation of object
    • Serializable::unserialize - Constructs the object
    • serialize - Generates a storable representation of a value
    • Session::close - Close session
    • Session::createSchema - Create new schema
    • Session::dropSchema - Drop a schema
    • Session::generateUUID - Get new UUID
    • Session::getDefaultSchema - Get default schema name
    • Session::getSchema - Get a new schema object
    • Session::getSchemas - Get the schemas
    • Session::getServerVersion - Get server version
    • Session::listClients - Get client list
    • Session::quoteName - Add quotes
    • Session::releaseSavepoint - Release set savepoint
    • Session::rollback - Rollback transaction
    • Session::rollbackTo - Rollback transaction to savepoint
    • Session::setSavepoint - Create savepoint
    • Session::sql - Execute SQL query
    • Session::startTransaction - Start transaction
    • Session::__construct - Description constructor
    • SessionHandler::close - Close the session
    • SessionHandler::create_sid - Return a new session ID
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - Write session data
    • SessionHandlerInterface::close - Close the session
    • SessionHandlerInterface::destroy - Destroy a session
    • SessionHandlerInterface::gc - Cleanup old sessions
    • SessionHandlerInterface::open - Initialize session
    • SessionHandlerInterface::read - Read session data
    • SessionHandlerInterface::write - Write session data
    • SessionIdInterface::create_sid - Create session ID
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Update timestamp
    • SessionUpdateTimestampHandlerInterface::validateId - Validate ID
    • session_abort - Discard session array changes and finish session
    • session_cache_expire - Get and/or set current cache expire
    • session_cache_limiter - Get and/or set the current cache limiter
    • session_commit - Alias of session_write_close
    • session_create_id - Create new session id
    • session_decode - Decodes session data from a session encoded string
    • session_destroy - Destroys all data registered to a session
    • session_encode - Encodes the current session data as a session encoded string
    • session_gc - Perform session data garbage collection
    • session_get_cookie_params - Get the session cookie parameters
    • session_id - Get and/or set the current session id
    • session_module_name - Get and/or set the current session module
    • session_name - Get and/or set the current session name
    • session_regenerate_id - Update the current session id with a newly generated one
    • session_register_shutdown - Session shutdown function
    • session_reset - Re-initialize session array with original values
    • session_save_path - Get and/or set the current session save path
    • session_set_cookie_params - Set the session cookie parameters
    • session_set_save_handler - Sets user-level session storage functions
    • session_start - Start new or resume existing session
    • session_status - Returns the current session status
    • session_unset - Free all session variables
    • session_write_close - Write session data and end session
    • setcookie - Send a cookie
    • setlocale - Set locale information
    • setrawcookie - Send a cookie without urlencoding the cookie value
    • settype - Set the type of a variable
    • set_error_handler - Sets a user-defined error handler function
    • set_exception_handler - Sets a user-defined exception handler function
    • set_file_buffer - Alias of stream_set_write_buffer
    • set_include_path - Sets the include_path configuration option
    • set_time_limit - Limits the maximum execution time
    • sha1 - Calculate the sha1 hash of a string
    • sha1_file - Calculate the sha1 hash of a file
    • shell_exec - Execute command via shell and return the complete output as a string
    • shmop_close - Close shared memory block
    • shmop_delete - Delete shared memory block
    • shmop_open - Create or open shared memory block
    • shmop_read - Read data from shared memory block
    • shmop_size - Get size of shared memory block
    • shmop_write - Write data into shared memory block
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - Alias of highlight_file
    • shuffle - Shuffle an array
    • simdjson_decode - Decodes a JSON string
    • simdjson_is_valid - Check if a JSON string is valid
    • simdjson_key_count - Returns the value at a JSON pointer.
    • simdjson_key_exists - Check if the JSON contains the value referred to by a JSON pointer.
    • simdjson_key_value - Decodes the value of a JSON string located at the requested JSON pointer.
    • similar_text - Calculate the similarity between two strings
    • SimpleXMLElement::addAttribute - Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild - Adds a child element to the XML node
    • SimpleXMLElement::asXML - Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes - Identifies an element's attributes
    • SimpleXMLElement::children - Finds children of given node
    • 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 - Returns namespaces declared in document
    • SimpleXMLElement::getName - Gets the name of the XML element
    • SimpleXMLElement::getNamespaces - Returns namespaces used in document
    • SimpleXMLElement::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLElement::key - Return current key
    • SimpleXMLElement::next - Move to next element
    • SimpleXMLElement::registerXPathNamespace - Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::rewind - Rewind to the first element
    • SimpleXMLElement::saveXML - Alias of SimpleXMLElement::asXML
    • SimpleXMLElement::valid - Check whether the current element is valid
    • SimpleXMLElement::xpath - Runs XPath query on XML data
    • SimpleXMLElement::__construct - Creates a new SimpleXMLElement object
    • SimpleXMLElement::__toString - Returns the string content
    • simplexml_import_dom - Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file - Interprets an XML file into an object
    • simplexml_load_string - Interprets a string of XML into an object
    • sin - Sine
    • sinh - Hyperbolic sine
    • sizeof - Alias of count
    • sleep - Delay execution
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - Fetch an SNMP object
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - Return all objects including their respective object ID within the specified one
    • snmpset - Set the value of an SNMP object
    • snmpwalk - Fetch all the SNMP objects from an agent
    • snmpwalkoid - Query for a tree of information about a network entity
    • snmp_get_quick_print - Fetches the current value of the NET-SNMP library's quick_print setting
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Alias of snmp_set_oid_output_format
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Set the value of enable within the NET-SNMP library
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::__call - Calls a SOAP function (deprecated)
    • SoapClient::__construct - SoapClient constructor
    • SoapClient::__doRequest - Performs a SOAP request
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Returns list of available SOAP functions
    • SoapClient::__getLastRequest - Returns last SOAP request
    • SoapClient::__getLastRequestHeaders - Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse - Returns last SOAP response
    • SoapClient::__getLastResponseHeaders - Returns the SOAP headers from the last response
    • SoapClient::__getTypes - Returns a list of SOAP types
    • SoapClient::__setCookie - Defines a cookie for SOAP requests
    • SoapClient::__setLocation - Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders - Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall - Calls a SOAP function
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Sets the class which handles SOAP requests
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::__construct - SoapVar constructor
    • Socket context options - Socket context option listing
    • socket_accept - Accepts a connection on a 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 - Binds a name to a socket
    • socket_clear_error - Clears the error on the socket or the last error code
    • socket_close - Closes a Socket instance
    • socket_cmsg_space - Calculate message buffer size
    • socket_connect - Initiates a connection on a socket
    • socket_create - Create a socket (endpoint for communication)
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - Alias of socket_get_option
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - Alias of stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - Receives data from a connected socket
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_recvmsg - Read a message
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendmsg - Send a message
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_setopt - Alias of socket_set_option
    • socket_set_block - Sets blocking mode on a socket
    • socket_set_blocking - Alias of stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - Alias of stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • socket_wsaprotocol_info_export - Exports the WSAPROTOCOL_INFO Structure
    • socket_wsaprotocol_info_import - Imports a Socket from another Process
    • socket_wsaprotocol_info_release - Releases an exported WSAPROTOCOL_INFO Structure
    • sodium_add - Add large numbers
    • sodium_base642bin - Decodes a base64-encoded string into raw binary.
    • sodium_bin2base64 - Encodes a raw binary string with base64.
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Verify then decrypt a message with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt then authenticate with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Generate a random AES-256-GCM key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify then decrypt with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt then authenticate with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen - Generate a random ChaCha20-Poly1305 (IETF) key.
    • sodium_crypto_aead_chacha20poly1305_keygen - Generate a random ChaCha20-Poly1305 key.
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - (Preferred) Verify then decrypt with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Generate a random XChaCha20-Poly1305 key.
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Generate a random key for sodium_crypto_auth
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Authenticated public-key encryption
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Create a unified keypair string from a secret key and public key
    • sodium_crypto_box_open - Authenticated public-key decryption
    • sodium_crypto_box_publickey - Extract the public key from a crypto_box keypair
    • sodium_crypto_box_publickey_from_secretkey - Calculate the public key from a secret key
    • sodium_crypto_box_seal - Anonymous public-key encryption
    • sodium_crypto_box_seal_open - Anonymous public-key decryption
    • sodium_crypto_box_secretkey - Extracts the secret key from a crypto_box keypair
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_core_ristretto255_add - Adds an element
    • sodium_crypto_core_ristretto255_from_hash - Maps a vector
    • sodium_crypto_core_ristretto255_is_valid_point - Determines if a point on the ristretto255 curve
    • sodium_crypto_core_ristretto255_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_add - Adds a scalar value
    • sodium_crypto_core_ristretto255_scalar_complement - The sodium_crypto_core_ristretto255_scalar_complement purpose
    • sodium_crypto_core_ristretto255_scalar_invert - Inverts a scalar value
    • sodium_crypto_core_ristretto255_scalar_mul - Multiplies a scalar value
    • sodium_crypto_core_ristretto255_scalar_negate - Negates a scalar value
    • sodium_crypto_core_ristretto255_scalar_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_reduce - Reduces a scalar value
    • sodium_crypto_core_ristretto255_scalar_sub - Subtracts a scalar value
    • sodium_crypto_core_ristretto255_sub - Subtracts an element
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash for streaming
    • sodium_crypto_generichash_keygen - Generate a random generichash key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Generate a random root key for the KDF interface
    • sodium_crypto_kx_client_session_keys - Calculate the client-side session keys.
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Extract the public key from a crypto_kx keypair
    • sodium_crypto_kx_secretkey - Extract the secret key from a crypto_kx keypair.
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Calculate the server-side session keys.
    • sodium_crypto_pwhash - Derive a key from a password, using Argon2
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password, using scrypt
    • sodium_crypto_pwhash_scryptsalsa208sha256_str - Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify - Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_str - Get an ASCII-encoded hash
    • sodium_crypto_pwhash_str_needs_rehash - Determine whether or not to rehash a password
    • sodium_crypto_pwhash_str_verify - Verifies that a password matches a hash
    • sodium_crypto_scalarmult - Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_scalarmult_base - Alias of sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_scalarmult_ristretto255 - Computes a shared secret
    • sodium_crypto_scalarmult_ristretto255_base - Calculates the public key from a secret key
    • sodium_crypto_secretbox - Authenticated shared-key encryption
    • sodium_crypto_secretbox_keygen - Generate random key for sodium_crypto_secretbox
    • sodium_crypto_secretbox_open - Authenticated shared-key decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Initialize a secretstream context for decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Initialize a secretstream context for encryption
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Generate a random secretstream key.
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Decrypt a chunk of data from an encrypted stream
    • sodium_crypto_secretstream_xchacha20poly1305_push - Encrypt a chunk of data so that it can safely be decrypted in a streaming API
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Explicitly rotate the key in the secretstream state
    • sodium_crypto_shorthash - Compute a short hash of a message and key
    • sodium_crypto_shorthash_keygen - Get random bytes for key
    • sodium_crypto_sign - Sign a message
    • sodium_crypto_sign_detached - Sign the message
    • sodium_crypto_sign_ed25519_pk_to_curve25519 - Convert an Ed25519 public key to a Curve25519 public key
    • sodium_crypto_sign_ed25519_sk_to_curve25519 - Convert an Ed25519 secret key to a Curve25519 secret key
    • sodium_crypto_sign_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_keypair_from_secretkey_and_publickey - Join a secret key and public key together
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Extract the Ed25519 public key from a keypair
    • sodium_crypto_sign_publickey_from_secretkey - Extract the Ed25519 public key from the secret key
    • sodium_crypto_sign_secretkey - Extract the Ed25519 secret key from a keypair
    • sodium_crypto_sign_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_sign_verify_detached - Verify signature for the message
    • sodium_crypto_stream - Generate a deterministic sequence of bytes from a seed
    • sodium_crypto_stream_keygen - Generate a random sodium_crypto_stream key.
    • sodium_crypto_stream_xchacha20 - Expands the key and nonce into a keystream of pseudorandom bytes
    • sodium_crypto_stream_xchacha20_keygen - Returns a secure random key
    • sodium_crypto_stream_xchacha20_xor - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xchacha20_xor_ic - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xor - Encrypt a message without authentication
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite a string with NUL characters
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getById - Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::system - Retrieve Solr Server information
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrCollapseFunction::getField - Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint - Returns collapse hint
    • SolrCollapseFunction::getMax - Returns max parameter
    • SolrCollapseFunction::getMin - Returns min parameter
    • SolrCollapseFunction::getNullPolicy - Returns null policy
    • SolrCollapseFunction::getSize - Returns size parameter
    • SolrCollapseFunction::setField - Sets the field to collapse on
    • SolrCollapseFunction::setHint - Sets collapse hint
    • SolrCollapseFunction::setMax - Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy - Sets the NULL Policy
    • SolrCollapseFunction::setSize - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__construct - Constructor
    • SolrCollapseFunction::__toString - Returns a string representing the constructed collapse function
    • SolrDisMaxQuery::addBigramPhraseField - Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery - Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField - Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField - Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField - Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField - Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::removeBigramPhraseField - Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery - Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField - Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField - Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField - Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField - Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop - Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction - Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery - Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch - Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop - Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt - Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop - Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker - Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields - Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop - Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields - Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser - Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser - Switch QueryParser to be EDisMax
    • SolrDisMaxQuery::__construct - Class Constructor
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - Alias of 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 of 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 of SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - Alias of 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 of 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 - Sort an array in ascending order
    • soundex - Calculate the soundex key of a string
    • SplDoublyLinkedList::add - Add/insert a new value at the specified index
    • SplDoublyLinkedList::bottom - Peeks at the node from the beginning of the doubly linked list
    • SplDoublyLinkedList::count - Counts the number of elements in the doubly linked list
    • SplDoublyLinkedList::current - Return current array entry
    • SplDoublyLinkedList::getIteratorMode - Returns the mode of iteration
    • SplDoublyLinkedList::isEmpty - Checks whether the doubly linked list is empty
    • SplDoublyLinkedList::key - Return current node index
    • SplDoublyLinkedList::next - Move to next entry
    • SplDoublyLinkedList::offsetExists - Returns whether the requested $index exists
    • SplDoublyLinkedList::offsetGet - Returns the value at the specified $index
    • SplDoublyLinkedList::offsetSet - Sets the value at the specified $index to $value
    • SplDoublyLinkedList::offsetUnset - Unsets the value at the specified $index
    • SplDoublyLinkedList::pop - Pops a node from the end of the doubly linked list
    • SplDoublyLinkedList::prev - Move to previous entry
    • SplDoublyLinkedList::push - Pushes an element at the end of the doubly linked list
    • SplDoublyLinkedList::rewind - Rewind iterator back to the start
    • SplDoublyLinkedList::serialize - Serializes the storage
    • SplDoublyLinkedList::setIteratorMode - Sets the mode of iteration
    • SplDoublyLinkedList::shift - Shifts a node from the beginning of the doubly linked list
    • SplDoublyLinkedList::top - Peeks at the node from the end of the doubly linked list
    • SplDoublyLinkedList::unserialize - Unserializes the storage
    • SplDoublyLinkedList::unshift - Prepends the doubly linked list with an element
    • SplDoublyLinkedList::valid - Check whether the doubly linked list contains more nodes
    • SplFileInfo::getATime - Gets last access time of the file
    • SplFileInfo::getBasename - Gets the base name of the file
    • SplFileInfo::getCTime - Gets the inode change time
    • SplFileInfo::getExtension - Gets the file extension
    • SplFileInfo::getFileInfo - Gets an SplFileInfo object for the file
    • SplFileInfo::getFilename - Gets the filename
    • SplFileInfo::getGroup - Gets the file group
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Gets the last modified time
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Gets file size
    • SplFileInfo::getType - Gets file type
    • SplFileInfo::isDir - Tells if the file is a directory
    • SplFileInfo::isExecutable - Tells if the file is executable
    • SplFileInfo::isFile - Tells if the object references a regular file
    • SplFileInfo::isLink - Tells if the file is a link
    • SplFileInfo::isReadable - Tells if file is readable
    • SplFileInfo::isWritable - Tells if the entry is writable
    • SplFileInfo::openFile - Gets an SplFileObject object for the file
    • SplFileInfo::setFileClass - Sets the class used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
    • SplFileInfo::__construct - Construct a new SplFileInfo object
    • SplFileInfo::__toString - Returns the path to the file as a string
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Reached end of file
    • SplFileObject::fflush - Flushes the output to the file
    • SplFileObject::fgetc - Gets character from file
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Gets line from file
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Portable file locking
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Write a field array as a CSV line
    • SplFileObject::fread - Read from file
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Gets information about the file
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Write to file
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Get the delimiter, enclosure and escape character for CSV
    • SplFileObject::getCurrentLine - Alias of 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 - Register and return default file extensions for spl_autoload
    • spl_autoload_functions - Return all registered __autoload() functions
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - 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 - Return a formatted string
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close - Closes the database connection
    • SQLite3::createAggregate - Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation - Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions - Enable throwing exceptions
    • SQLite3::escapeString - Returns a string that has been properly escaped
    • SQLite3::exec - Executes a result-less query against a given database
    • SQLite3::lastErrorCode - Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg - Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension - Attempts to load an SQLite extension library
    • SQLite3::open - Opens an SQLite database
    • SQLite3::openBlob - Opens a stream resource to read a BLOB
    • SQLite3::prepare - Prepares an SQL statement for execution
    • SQLite3::query - Executes an SQL query
    • SQLite3::querySingle - Executes a query and returns a single result
    • SQLite3::setAuthorizer - Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize - Closes the result set
    • SQLite3Result::numColumns - Returns the number of columns in the result set
    • SQLite3Result::reset - Resets the result set back to the first row
    • SQLite3Result::__construct - Constructs an SQLite3Result
    • SQLite3Stmt::bindParam - Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue - Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear - Clears all current bound parameters
    • SQLite3Stmt::close - Closes the prepared statement
    • SQLite3Stmt::execute - Executes a prepared statement and returns a result set object
    • SQLite3Stmt::getSQL - Get the SQL of the statement
    • SQLite3Stmt::paramCount - Returns the number of parameters within the prepared statement
    • SQLite3Stmt::readOnly - Returns whether a statement is definitely read only
    • SQLite3Stmt::reset - Resets the prepared statement
    • SQLite3Stmt::__construct - Constructs an SQLite3Stmt object
    • sqlsrv_begin_transaction - Begins a database transaction
    • sqlsrv_cancel - Cancels a statement
    • sqlsrv_client_info - Returns information about the client and specified connection
    • sqlsrv_close - Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit - Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure - Changes the driver error handling and logging configurations
    • sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors - Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch - Makes the next row in a result set available for reading
    • sqlsrv_fetch_array - Returns a row as an array
    • sqlsrv_fetch_object - Retrieves the next row of data in a result set as an object
    • sqlsrv_field_metadata - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • SqlStatement::bind - Bind statement parameters
    • SqlStatement::execute - Execute the operation
    • SqlStatement::getNextResult - Get next result
    • SqlStatement::getResult - Get result
    • SqlStatement::hasMoreResults - Check for more results
    • SqlStatement::__construct - Description constructor
    • SqlStatementResult::fetchAll - Get all rows from result
    • SqlStatementResult::fetchOne - Get single row
    • SqlStatementResult::getAffectedItemsCount - Get affected row count
    • SqlStatementResult::getColumnNames - Get column names
    • SqlStatementResult::getColumns - Get columns
    • SqlStatementResult::getColumnsCount - Get column count
    • SqlStatementResult::getGeneratedIds - Get generated ids
    • SqlStatementResult::getLastInsertId - Get last insert id
    • SqlStatementResult::getWarnings - Get warnings from last operation
    • SqlStatementResult::getWarningsCount - Get warning count from last operation
    • SqlStatementResult::hasData - Check if result has data
    • SqlStatementResult::nextResult - Get next result
    • SqlStatementResult::__construct - Description constructor
    • sqrt - Square root
    • srand - Seed the random number generator
    • sscanf - Parses input from a string according to a 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 context options - SSL context option listing
    • stat - Gives information about a file
    • Statement::getNextResult - Get next result
    • Statement::getResult - Get result
    • Statement::hasMoreResults - Check if more results
    • Statement::__construct - Description constructor
    • stats_absolute_deviation - Returns the absolute deviation of an array of values
    • stats_cdf_beta - Calculates any one parameter of the beta distribution given values for the others
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others
    • stats_cdf_cauchy - Calculates any one parameter of the Cauchy distribution given values for the others
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others
    • stats_cdf_exponential - Calculates any one parameter of the exponential distribution given values for the others
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others
    • stats_cdf_laplace - Calculates any one parameter of the Laplace distribution given values for the others
    • stats_cdf_logistic - Calculates any one parameter of the logistic distribution given values for the others
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others
    • stats_cdf_noncentral_f - Calculates any one parameter of the non-central F distribution given values for the others
    • stats_cdf_noncentral_t - Calculates any one parameter of the non-central t-distribution give values for the others
    • stats_cdf_normal - Calculates any one parameter of the normal distribution given values for the others
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others
    • stats_cdf_t - Calculates any one parameter of the t-distribution given values for the others
    • stats_cdf_uniform - Calculates any one parameter of the uniform distribution given values for the others
    • stats_cdf_weibull - Calculates any one parameter of the Weibull distribution given values for the others
    • stats_covariance - Computes the covariance of two data sets
    • stats_dens_beta - Probability density function of the beta distribution
    • stats_dens_cauchy - Probability density function of the Cauchy distribution
    • stats_dens_chisquare - Probability density function of the chi-square distribution
    • stats_dens_exponential - Probability density function of the exponential distribution
    • stats_dens_f - Probability density function of the F distribution
    • stats_dens_gamma - Probability density function of the gamma distribution
    • stats_dens_laplace - Probability density function of the Laplace distribution
    • stats_dens_logistic - Probability density function of the logistic distribution
    • stats_dens_normal - Probability density function of the normal distribution
    • stats_dens_pmf_binomial - Probability mass function of the binomial distribution
    • stats_dens_pmf_hypergeometric - Probability mass function of the hypergeometric distribution
    • stats_dens_pmf_negative_binomial - Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson - Probability mass function of the Poisson distribution
    • stats_dens_t - Probability density function of the t-distribution
    • stats_dens_uniform - Probability density function of the uniform distribution
    • stats_dens_weibull - Probability density function of the Weibull distribution
    • stats_harmonic_mean - Returns the harmonic mean of an array of values
    • stats_kurtosis - Computes the kurtosis of the data in the array
    • stats_rand_gen_beta - Generates a random deviate from the beta distribution
    • stats_rand_gen_chisquare - Generates a random deviate from the chi-square distribution
    • stats_rand_gen_exponential - Generates a random deviate from the exponential distribution
    • stats_rand_gen_f - Generates a random deviate from the F distribution
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates a random deviate from the gamma distribution
    • stats_rand_gen_ibinomial - Generates a random deviate from the binomial distribution
    • stats_rand_gen_ibinomial_negative - Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_int - Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare - Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F distribution
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a non-central t-distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution
    • stats_rand_gen_t - Generates a single random deviate from a t-distribution
    • stats_rand_get_seeds - Get the seed values of the random number generator
    • stats_rand_phrase_to_seeds - Generate two seeds for the RGN random number generator
    • stats_rand_ranf - Generates a random floating point number between 0 and 1
    • stats_rand_setall - Set seed values to the random generator
    • stats_skew - Computes the skewness of the data in the array
    • stats_standard_deviation - Returns the standard deviation
    • stats_stat_binomial_coef - Returns a binomial coefficient
    • stats_stat_correlation - Returns the Pearson correlation coefficient of two data sets
    • stats_stat_factorial - Returns the factorial of an integer
    • stats_stat_independent_t - Returns the t-value from the independent two-sample t-test
    • stats_stat_innerproduct - Returns the inner product of two vectors
    • stats_stat_paired_t - Returns the t-value of the dependent t-test for paired samples
    • stats_stat_percentile - Returns the percentile value
    • stats_stat_powersum - Returns the power sum of a vector
    • stats_variance - Returns the variance
    • Stomp::abort - Rolls back a transaction in progress
    • Stomp::ack - Acknowledges consumption of a message
    • Stomp::begin - Starts a transaction
    • Stomp::commit - Commits a transaction in progress
    • Stomp::error - Gets the last stomp error
    • Stomp::getReadTimeout - Gets read timeout
    • Stomp::getSessionId - Gets the current stomp session ID
    • Stomp::hasFrame - Indicates whether or not there is a frame ready to read
    • Stomp::readFrame - Reads the next frame
    • Stomp::send - Sends a message
    • Stomp::setReadTimeout - Sets read timeout
    • Stomp::subscribe - Registers to listen to a given destination
    • Stomp::unsubscribe - Removes an existing subscription
    • Stomp::__construct - Opens a connection
    • Stomp::__destruct - Closes stomp connection
    • StompException::getDetails - Get exception details
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Returns a string description of the last connect error
    • stomp_version - Gets the current stomp extension version
    • strcasecmp - Binary safe case-insensitive string comparison
    • strchr - Alias of strstr
    • strcmp - Binary safe string comparison
    • strcoll - Locale based string comparison
    • strcspn - Find length of initial segment not matching mask
    • 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 of 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 - Format a local time/date according to locale settings
    • Stringable::__toString - Gets a string representation of the object
    • stripcslashes - Un-quote string quoted with addcslashes
    • stripos - Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes - Un-quotes a quoted string
    • strip_tags - Strip HTML and PHP tags from a string
    • stristr - Case-insensitive strstr
    • strlen - Get string length
    • strnatcasecmp - Case insensitive string comparisons using a "natural order" algorithm
    • strnatcmp - String comparisons using a "natural order" algorithm
    • strncasecmp - Binary safe case-insensitive string comparison of the first n characters
    • strncmp - Binary safe string comparison of the first n characters
    • strpbrk - Search a string for any of a set of characters
    • strpos - Find the position of the first occurrence of a substring in a string
    • strptime - Parse a time/date generated with strftime
    • strrchr - Find the last occurrence of a character in a string
    • strrev - Reverse a string
    • strripos - Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos - Find the position of the last occurrence of a substring in a string
    • strspn - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask
    • strstr - Find the first occurrence of a string
    • strtok - Tokenize string
    • strtolower - Make a string lowercase
    • strtotime - Parse about any English textual datetime description into a Unix timestamp
    • strtoupper - Make a string uppercase
    • strtr - Translate characters or replace substrings
    • strval - Get string value of a 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 - Parse a CSV string into an array
    • str_increment - Increment an alphanumeric string
    • str_ireplace - Case-insensitive version of str_replace
    • str_pad - Pad a string to a certain length with another string
    • str_repeat - Repeat a string
    • str_replace - Replace all occurrences of the search string with the replacement string
    • str_rot13 - Perform the rot13 transform on a string
    • str_shuffle - Randomly shuffles a string
    • str_split - Convert a string to an array
    • str_starts_with - Checks if a string starts with a given substring
    • str_word_count - Return information about words used in a string
    • substr - Return part of a string
    • substr_compare - Binary safe comparison of two strings from an offset, up to length characters
    • substr_count - Count the number of substring occurrences
    • substr_replace - Replace text within a portion of a string
    • SVM::crossvalidate - Test training params on subsets of the training data
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Schedules the addition of an item in a working directory
    • svn_auth_get_parameter - Retrieves authentication parameter
    • svn_auth_set_parameter - Sets an authentication parameter
    • svn_blame - Get the SVN blame for a file
    • svn_cat - Returns the contents of a file in a repository
    • svn_checkout - Checks out a working copy from the repository
    • svn_cleanup - Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version - Returns the version of the SVN client libraries
    • svn_commit - Sends changes from the local working copy to the repository
    • svn_delete - Delete items from a working copy or repository
    • svn_diff - Recursively diffs two paths
    • svn_export - Export the contents of a SVN directory
    • svn_fs_abort_txn - Aborts a transaction
    • svn_fs_apply_text - Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 - Create a new transaction
    • svn_fs_change_node_prop - Return true if everything is ok, false otherwise
    • svn_fs_check_path - Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed - Return true if content is different, false otherwise
    • svn_fs_copy - Copies a file or a directory
    • svn_fs_delete - Deletes a file or a directory
    • svn_fs_dir_entries - Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents - Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length - Returns the length of a file from a given version of the fs
    • svn_fs_is_dir - Determines if a path points to a directory
    • svn_fs_is_file - Determines if a path points to a file
    • svn_fs_make_dir - Creates a new empty directory
    • svn_fs_make_file - Creates a new empty file
    • svn_fs_node_created_rev - Returns the revision in which path under fsroot was created
    • svn_fs_node_prop - Returns the value of a property for a node
    • svn_fs_props_changed - Return true if props are different, false otherwise
    • svn_fs_revision_prop - Fetches the value of a named property
    • svn_fs_revision_root - Get a handle on a specific version of the repository root
    • svn_fs_txn_root - Creates and returns a transaction root
    • svn_fs_youngest_rev - Returns the number of the youngest revision in the filesystem
    • svn_import - Imports an unversioned path into a repository
    • svn_log - Returns the commit log messages of a repository URL
    • svn_ls - Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir - Creates a directory in a working copy or repository
    • svn_repos_create - Create a new subversion repository at path
    • svn_repos_fs - Gets a handle on the filesystem for a repository
    • svn_repos_fs_begin_txn_for_commit - Create a new transaction
    • svn_repos_fs_commit_txn - Commits a transaction and returns the new revision
    • svn_repos_hotcopy - Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open - Open a shared lock on a repository
    • svn_repos_recover - Run recovery procedures on the repository located at path
    • svn_revert - Revert changes to the working copy
    • svn_status - Returns the status of working copy files and directories
    • svn_update - Update working copy
    • Swoole\Async::dnsLookup - Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read - Read file stream asynchronously.
    • Swoole\Async::readFile - Read a file asynchronously.
    • Swoole\Async::set - Update the async I/O options.
    • Swoole\Async::write - Write data to a file stream asynchronously.
    • Swoole\Async::writeFile - Description
    • Swoole\Atomic::add - Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset - Compare and set the value of the atomic object.
    • Swoole\Atomic::get - Get the current value of the atomic object.
    • Swoole\Atomic::set - Set a new value to the atomic object.
    • Swoole\Atomic::sub - Subtract a number to the value of the atomic object.
    • Swoole\Atomic::__construct - Construct a swoole atomic object.
    • Swoole\Buffer::append - Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear - Reset the memory buffer.
    • Swoole\Buffer::expand - Expand the size of memory buffer.
    • Swoole\Buffer::read - Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle - Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr - Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::write - Write data to the memory buffer. The memory allocated for the buffer will not be changed.
    • Swoole\Buffer::__construct - Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct - Destruct the Swoole memory buffer.
    • Swoole\Buffer::__toString - Get the string value of the memory buffer.
    • Swoole\Channel::pop - Read and pop data from swoole channel.
    • Swoole\Channel::push - Write and push data into Swoole channel.
    • Swoole\Channel::stats - Get stats of swoole channel.
    • Swoole\Channel::__construct - Construct a Swoole Channel
    • Swoole\Channel::__destruct - Destruct a Swoole channel.
    • Swoole\Client::close - Close the connection established.
    • Swoole\Client::connect - Connect to the remote TCP or UDP port.
    • Swoole\Client::getpeername - Get the remote socket name of the connection.
    • Swoole\Client::getsockname - Get the local socket name of the connection.
    • Swoole\Client::isConnected - Check if the connection is established.
    • Swoole\Client::on - Add callback functions triggered by events.
    • Swoole\Client::pause - Pause receiving data.
    • Swoole\Client::pipe - Redirect the data to another file descriptor.
    • Swoole\Client::recv - Receive data from the remote socket.
    • Swoole\Client::resume - Resume receiving data.
    • Swoole\Client::send - Send data to the remote TCP socket.
    • Swoole\Client::sendfile - Send file to the remote TCP socket.
    • Swoole\Client::sendto - Send data to the remote UDP address.
    • Swoole\Client::set - Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep - Remove the TCP client from system event loop.
    • Swoole\Client::wakeup - Add the TCP client back into the system event loop.
    • Swoole\Client::__construct - Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct - Destruct the Swoole client.
    • Swoole\Connection\Iterator::count - Count connections.
    • Swoole\Connection\Iterator::current - Return current connection entry.
    • Swoole\Connection\Iterator::key - Return key of the current connection.
    • Swoole\Connection\Iterator::next - Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists - Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet - Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet - Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset - Unset an offset.
    • Swoole\Connection\Iterator::rewind - Rewinds iterator
    • Swoole\Connection\Iterator::valid - Check if current position is valid.
    • Swoole\Coroutine::call_user_func - Call a callback given by the first parameter
    • Swoole\Coroutine::call_user_func_array - Call a callback with an array of parameters
    • Swoole\Coroutine::cli_wait - Description
    • Swoole\Coroutine::create - Description
    • Swoole\Coroutine::getuid - Description
    • Swoole\Coroutine::resume - Description
    • Swoole\Coroutine::suspend - Description
    • Swoole\Coroutine\Client::close - Description
    • Swoole\Coroutine\Client::connect - Description
    • Swoole\Coroutine\Client::getpeername - Description
    • Swoole\Coroutine\Client::getsockname - Description
    • Swoole\Coroutine\Client::isConnected - Description
    • Swoole\Coroutine\Client::recv - Description
    • Swoole\Coroutine\Client::send - Description
    • Swoole\Coroutine\Client::sendfile - Description
    • Swoole\Coroutine\Client::sendto - Description
    • Swoole\Coroutine\Client::set - Description
    • Swoole\Coroutine\Client::__construct - Description
    • Swoole\Coroutine\Client::__destruct - Description
    • Swoole\Coroutine\Http\Client::addFile - Description
    • Swoole\Coroutine\Http\Client::close - Description
    • Swoole\Coroutine\Http\Client::execute - Description
    • Swoole\Coroutine\Http\Client::get - Description
    • Swoole\Coroutine\Http\Client::getDefer - Description
    • Swoole\Coroutine\Http\Client::isConnected - Description
    • Swoole\Coroutine\Http\Client::post - Description
    • Swoole\Coroutine\Http\Client::recv - Description
    • Swoole\Coroutine\Http\Client::set - Description
    • Swoole\Coroutine\Http\Client::setCookies - Description
    • Swoole\Coroutine\Http\Client::setData - Description
    • Swoole\Coroutine\Http\Client::setDefer - Description
    • Swoole\Coroutine\Http\Client::setHeaders - Description
    • Swoole\Coroutine\Http\Client::setMethod - Description
    • Swoole\Coroutine\Http\Client::__construct - Description
    • Swoole\Coroutine\Http\Client::__destruct - Description
    • Swoole\Coroutine\MySQL::close - Description
    • Swoole\Coroutine\MySQL::connect - Description
    • Swoole\Coroutine\MySQL::getDefer - Description
    • Swoole\Coroutine\MySQL::query - Description
    • Swoole\Coroutine\MySQL::recv - Description
    • Swoole\Coroutine\MySQL::setDefer - Description
    • Swoole\Coroutine\MySQL::__construct - Description
    • Swoole\Coroutine\MySQL::__destruct - Description
    • Swoole\Event::add - Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer - Add a callback function to the next event loop.
    • Swoole\Event::del - Remove all event callback functions of a socket.
    • Swoole\Event::exit - Exit the eventloop, only available at client side.
    • Swoole\Event::set - Update the event callback functions of a socket.
    • Swoole\Event::wait - Description
    • Swoole\Event::write - Write data to the socket.
    • Swoole\Http\Client::addFile - Add a file to the post form.
    • Swoole\Http\Client::close - Close the http connection.
    • Swoole\Http\Client::download - Download a file from the remote server.
    • Swoole\Http\Client::execute - Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get - Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected - Check if the HTTP connection is connected.
    • Swoole\Http\Client::on - Register callback function by event name.
    • Swoole\Http\Client::post - Send POST http request to the remote server.
    • Swoole\Http\Client::push - Push data to websocket client.
    • Swoole\Http\Client::set - Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start - Start the swoole http server.
    • Swoole\Lock::lock - Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::lock_read - Lock a read-write lock for reading.
    • Swoole\Lock::trylock - Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::trylock_read - Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::unlock - Release the lock.
    • Swoole\Lock::__construct - Construct a memory lock.
    • Swoole\Lock::__destruct - Destory a Swoole memory lock.
    • Swoole\Mmap::open - Map a file into memory and return the stream resource which can be used by PHP stream operations.
    • Swoole\MySQL::close - Close the async MySQL connection.
    • Swoole\MySQL::connect - Connect to the remote MySQL server.
    • Swoole\MySQL::getBuffer - Description
    • Swoole\MySQL::on - Register callback function based on event name.
    • Swoole\MySQL::query - Run the SQL query.
    • Swoole\MySQL::__construct - Construct an async MySQL client.
    • Swoole\MySQL::__destruct - Destory the async MySQL client.
    • Swoole\Process::alarm - High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close - Close the pipe to the child process.
    • Swoole\Process::daemon - Change the process to be a daemon process.
    • Swoole\Process::exec - Execute system commands.
    • Swoole\Process::exit - Stop the child processes.
    • Swoole\Process::freeQueue - Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill - Send signal to the child process.
    • Swoole\Process::name - Set name of the process.
    • Swoole\Process::pop - Read and pop data from the message queue.
    • Swoole\Process::push - Write and push data into the message queue.
    • Swoole\Process::read - Read data sending to the process.
    • Swoole\Process::signal - Send signal to the child processes.
    • Swoole\Process::start - Start the process.
    • Swoole\Process::statQueue - Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue - Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait - Wait for the events of child processes.
    • Swoole\Process::write - Write data into the pipe and communicate with the parent process or child processes.
    • Swoole\Process::__construct - Construct a process.
    • Swoole\Process::__destruct - Destory the process.
    • Swoole\Redis\Server::format - Description
    • Swoole\Redis\Server::setHandler - Description
    • Swoole\Redis\Server::start - Description
    • Swoole\Serialize::pack - Serialize the data.
    • Swoole\Serialize::unpack - Unserialize the data.
    • Swoole\Server::addlistener - Add a new listener to the server.
    • Swoole\Server::addProcess - Add a user defined swoole_process to the server.
    • Swoole\Server::after - Trigger a callback function after a period of time.
    • Swoole\Server::bind - Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer - Stop and destory a timer.
    • Swoole\Server::close - Close a connection to the client.
    • Swoole\Server::confirm - Check status of the connection.
    • Swoole\Server::connection_info - Get the connection info by file description.
    • Swoole\Server::connection_list - Get all of the established connections.
    • Swoole\Server::defer - Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server::exist - Check if the connection is existed.
    • Swoole\Server::finish - Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo - Get the connection info by file description.
    • Swoole\Server::getClientList - Get all of the established connections.
    • Swoole\Server::getLastError - Get the error code of the most recent error.
    • Swoole\Server::heartbeat - Check all the connections on the server.
    • Swoole\Server::listen - Listen on the given IP and port, socket type.
    • Swoole\Server::on - Register a callback function by event name.
    • Swoole\Server::pause - Stop receiving data from the connection.
    • Swoole\Server::protect - Set the connection to be protected mode.
    • Swoole\Server::reload - Restart all the worker process.
    • Swoole\Server::resume - Start receving data from the connection.
    • Swoole\Server::send - Send data to the client.
    • Swoole\Server::sendfile - Send file to the connection.
    • Swoole\Server::sendMessage - Send message to worker processes by ID.
    • Swoole\Server::sendto - Send data to the remote UDP address.
    • Swoole\Server::sendwait - Send data to the remote socket in the blocking way.
    • Swoole\Server::set - Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown - Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start - Start the Swoole server.
    • Swoole\Server::stats - Get the stats of the Swoole server.
    • Swoole\Server::stop - Stop the Swoole server.
    • Swoole\Server::task - Send data to the task worker processes.
    • Swoole\Server::taskwait - Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti - Execute multiple tasks concurrently.
    • Swoole\Server::tick - Repeats a given function at every given time-interval.
    • Swoole\Server::__construct - Construct a Swoole server.
    • Swoole\Server\Port::on - Register callback functions by event.
    • Swoole\Server\Port::set - Set protocol of the server port.
    • Swoole\Server\Port::__construct - Construct a server port
    • Swoole\Server\Port::__destruct - Destory server port
    • Swoole\Table::column - Set the data type and size of the columns.
    • Swoole\Table::count - Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create - Create the swoole memory table.
    • Swoole\Table::current - Get the current row.
    • Swoole\Table::decr - Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del - Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy - Destroy the Swoole table.
    • Swoole\Table::exist - Check if a row is existed by $row_key.
    • Swoole\Table::get - Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr - Increment the value by $row_key and $column_key.
    • Swoole\Table::key - Get the key of current row.
    • Swoole\Table::next - Iterator the next row.
    • Swoole\Table::rewind - Rewind the iterator.
    • Swoole\Table::set - Update a row of the table by $row_key.
    • Swoole\Table::valid - Check current if the current row is valid.
    • Swoole\Table::__construct - Construct a Swoole memory table with fixed size.
    • Swoole\Timer::after - Trigger a callback function after a period of time.
    • Swoole\Timer::clear - Delete a timer by timer ID.
    • Swoole\Timer::exists - Check if a timer is existed.
    • Swoole\Timer::tick - Repeats a given function at every given time-interval.
    • Swoole\WebSocket\Server::exist - Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on - Register event callback function
    • Swoole\WebSocket\Server::pack - Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push - Push data to the remote client.
    • Swoole\WebSocket\Server::unpack - Unpack the binary data received from the client.
    • swoole_async_dns_lookup - Async and non-blocking hostname to IP lookup
    • swoole_async_read - Read file stream asynchronously
    • swoole_async_readfile - Read a file asynchronously
    • swoole_async_set - Update the async I/O options
    • swoole_async_write - Write data to a file stream asynchronously
    • swoole_async_writefile - Write data to a file asynchronously
    • swoole_clear_error - Clear errors in the socket or on the last error code
    • swoole_client_select - Get the file description which are ready to read/write or error
    • swoole_cpu_num - Get the number of CPU
    • swoole_errno - Get the error code of the latest system call
    • swoole_error_log - Output error messages to the log
    • swoole_event_add - Add new callback functions of a socket into the EventLoop
    • swoole_event_defer - Add callback function to the next event loop
    • swoole_event_del - Remove all event callback functions of a socket
    • swoole_event_exit - Exit the eventloop, only available at the client side
    • swoole_event_set - Update the event callback functions of a socket
    • swoole_event_wait - Start the event loop
    • swoole_event_write - Write data to a socket
    • swoole_get_local_ip - Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error - Get the lastest error message
    • swoole_load_module - Load a swoole extension
    • swoole_select - Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name - Set the process name
    • swoole_strerror - Convert the Errno into error messages
    • swoole_timer_after - Trigger a one time callback function in the future
    • swoole_timer_exists - Check if a timer callback function is existed
    • swoole_timer_tick - Trigger a timer tick callback function by time interval
    • swoole_version - Get the version of Swoole
    • symlink - Creates a symbolic 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 - Generate a system log message
    • system - Execute an external program and display the output
    • sys_getloadavg - Gets system load average
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • Table::count - Get row count
    • Table::delete - Delete rows from table
    • Table::existsInDatabase - Check if table exists in database
    • Table::getName - Get table name
    • Table::getSchema - Get table schema
    • Table::getSession - Get table session
    • Table::insert - Insert table rows
    • Table::isView - Check if table is view
    • Table::select - Select rows from table
    • Table::update - Update rows in table
    • Table::__construct - Table constructor
    • TableDelete::bind - Bind delete query parameters
    • TableDelete::execute - Execute delete query
    • TableDelete::limit - Limit deleted rows
    • TableDelete::orderby - Set delete sort criteria
    • TableDelete::where - Set delete search condition
    • TableDelete::__construct - TableDelete constructor
    • TableInsert::execute - Execute insert query
    • TableInsert::values - Add insert row values
    • TableInsert::__construct - TableInsert constructor
    • TableSelect::bind - Bind select query parameters
    • TableSelect::execute - Execute select statement
    • TableSelect::groupBy - Set select grouping criteria
    • TableSelect::having - Set select having condition
    • TableSelect::limit - Limit selected rows
    • TableSelect::lockExclusive - Execute EXCLUSIVE LOCK
    • TableSelect::lockShared - Execute SHARED LOCK
    • TableSelect::offset - Set limit offset
    • TableSelect::orderby - Set select sort criteria
    • TableSelect::where - Set select search condition
    • TableSelect::__construct - TableSelect constructor
    • TableUpdate::bind - Bind update query parameters
    • TableUpdate::execute - Execute update query
    • TableUpdate::limit - Limit update row count
    • TableUpdate::orderby - Set sorting criteria
    • TableUpdate::set - Add field to be updated
    • TableUpdate::where - Set search filter
    • TableUpdate::__construct - TableUpdate constructor
    • taint - Taint a string
    • tan - Tangent
    • tanh - Hyperbolic tangent
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Create file with unique file name
    • textdomain - Sets the default domain
    • Thread::getCreatorId - Identification
    • Thread::getCurrentThread - Identification
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::isJoined - State Detection
    • Thread::isStarted - State Detection
    • Thread::join - Synchronization
    • Thread::start - Execution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Runtime Manipulation
    • Threaded::isRunning - State Detection
    • Threaded::isTerminated - State Detection
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronization
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Execution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - Synchronization
    • Threaded::wait - Synchronization
    • Throwable::getCode - Gets the exception code
    • Throwable::getFile - Gets the file in which the object was created
    • Throwable::getLine - Gets the line on which the object was instantiated
    • Throwable::getMessage - Gets the message
    • Throwable::getPrevious - Returns the previous Throwable
    • Throwable::getTrace - Gets the stack trace
    • Throwable::getTraceAsString - Gets the stack trace as a string
    • Throwable::__toString - Gets a string representation of the thrown object
    • 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 - Return current Unix timestamp
    • timezone_abbreviations_list - Alias of DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Alias of DateTimeZone::listIdentifiers
    • timezone_location_get - Alias of DateTimeZone::getLocation
    • timezone_name_from_abbr - Returns a timezone name by guessing from abbreviation and UTC offset
    • timezone_name_get - Alias of DateTimeZone::getName
    • timezone_offset_get - Alias of DateTimeZone::getOffset
    • timezone_open - Alias of DateTimeZone::__construct
    • timezone_transitions_get - Alias of DateTimeZone::getTransitions
    • timezone_version_get - Gets the version of the timezonedb
    • time_nanosleep - Delay for a number of seconds and nanoseconds
    • time_sleep_until - Make the script sleep until the specified time
    • tmpfile - Creates a temporary file
    • token_get_all - Split given source into PHP tokens
    • token_name - Get the symbolic name of a given PHP token
    • touch - Sets access and modification time of file
    • 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 - Checks if the trait exists
    • 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 - Generates a user-level error/warning/notice message
    • trim - Strip whitespace (or other characters) from the beginning and end of a string
  • u
    • uasort - Sort an array with a user-defined comparison function and maintain index association
    • ucfirst - Make a string's first character uppercase
    • 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 - Uppercase the first character of each word in a string
    • 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 - Sort an array by keys using a user-defined comparison function
    • umask - Changes the current umask
    • uniqid - Generate a unique ID
    • UnitEnum::cases - Generates a list of cases on an enum
    • unixtojd - Convert Unix timestamp to Julian Day
    • unlink - Deletes a file
    • unpack - Unpack data from binary string
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - Creates a PHP value from a stored representation
    • unset - Unset a given variable
    • 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 - Decodes URL-encoded string
    • urlencode - URL-encodes string
    • user_error - Alias of trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Delay execution in microseconds
    • usort - Sort an array by values using a user-defined comparison function
    • utf8_decode - Converts a string from UTF-8 to ISO-8859-1, replacing invalid or unrepresentable characters
    • utf8_encode - Converts a string from ISO-8859-1 to UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant::__construct - variant class constructor
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - Concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::disconnect - Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - Dumps information about a variable
    • var_export - Outputs or returns a parsable string representation of a variable
    • var_representation - Returns a short, readable, parsable string representation of a variable
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Write a formatted string to a stream
    • virtual - Perform an Apache sub-request
    • vprintf - Output a formatted string
    • vsprintf - Return a formatted string
    • Vtiful\Kernel\Excel::addSheet - Vtiful\Kernel\Excel addSheet
    • Vtiful\Kernel\Excel::autoFilter - Vtiful\Kernel\Excel autoFilter
    • Vtiful\Kernel\Excel::constMemory - Vtiful\Kernel\Excel constMemory
    • Vtiful\Kernel\Excel::data - Vtiful\Kernel\Excel data
    • Vtiful\Kernel\Excel::fileName - Vtiful\Kernel\Excel fileName
    • Vtiful\Kernel\Excel::getHandle - Vtiful\Kernel\Excel getHandle
    • Vtiful\Kernel\Excel::header - Vtiful\Kernel\Excel header
    • Vtiful\Kernel\Excel::insertFormula - Vtiful\Kernel\Excel insertFormula
    • Vtiful\Kernel\Excel::insertImage - Vtiful\Kernel\Excel insertImage
    • Vtiful\Kernel\Excel::insertText - Vtiful\Kernel\Excel insertText
    • Vtiful\Kernel\Excel::mergeCells - Vtiful\Kernel\Excel mergeCells
    • Vtiful\Kernel\Excel::output - Vtiful\Kernel\Excel output
    • Vtiful\Kernel\Excel::setColumn - Vtiful\Kernel\Excel setColumn
    • Vtiful\Kernel\Excel::setRow - Vtiful\Kernel\Excel setRow
    • Vtiful\Kernel\Excel::__construct - Vtiful\Kernel\Excel constructor
    • Vtiful\Kernel\Format::align - Vtiful\Kernel\Format align
    • Vtiful\Kernel\Format::bold - Vtiful\Kernel\Format bold
    • Vtiful\Kernel\Format::italic - Vtiful\Kernel\Format italic
    • Vtiful\Kernel\Format::underline - Vtiful\Kernel\Format underline
  • w
    • Warning::__construct - Warning constructor
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::getIterator - Retrieve an external iterator
    • WeakMap::offsetExists - Checks whether a certain object is in the map
    • WeakMap::offsetGet - Returns the value pointed to by a certain object
    • WeakMap::offsetSet - Updates the map with a new key-value pair
    • WeakMap::offsetUnset - Removes an entry from the map
    • WeakReference::create - Create a new weak reference
    • WeakReference::get - Get a weakly referenced Object
    • WeakReference::__construct - Constructor that disallows instantiation
    • 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 - Wraps a string to a given number of characters
    • 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 of 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 of 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 of 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 of xdiff_string_bpatch
    • xdiff_string_rabdiff - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • xhprof_disable - Stops xhprof profiler
    • xhprof_enable - Start xhprof profiler
    • xhprof_sample_disable - Stops xhprof sample profiler
    • xhprof_sample_enable - Start XHProf profiling in sampling mode
    • XMLDiff\Base::diff - Produce diff of two XML documents
    • XMLDiff\Base::merge - Produce new XML document based on diff
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diff two DOMDocument objects
    • XMLDiff\DOM::merge - Produce merged DOMDocument
    • XMLDiff\File::diff - Diff two XML files
    • XMLDiff\File::merge - Produce merged XML document
    • XMLDiff\Memory::diff - Diff two XML documents
    • XMLDiff\Memory::merge - Produce merged XML document
    • XMLReader::close - Close the XMLReader input
    • XMLReader::expand - Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute - Get the value of a named attribute
    • XMLReader::getAttributeNo - Get the value of an attribute by index
    • XMLReader::getAttributeNs - Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty - Indicates if specified property has been set
    • XMLReader::isValid - Indicates if the parsed document is valid
    • XMLReader::lookupNamespace - Lookup namespace for a prefix
    • XMLReader::moveToAttribute - Move cursor to a named attribute
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToElement - Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute - Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute - Position cursor on the next Attribute
    • XMLReader::next - Move cursor to next node skipping all subtrees
    • XMLReader::open - Set the URI containing the XML to parse
    • XMLReader::read - Move to next node in document
    • XMLReader::readInnerXml - Retrieve XML from current node
    • XMLReader::readOuterXml - Retrieve XML from current node, including itself
    • XMLReader::readString - Reads the contents of the current node as a string
    • XMLReader::setParserProperty - Set parser options
    • XMLReader::setRelaxNGSchema - Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource - Set the data containing a RelaxNG Schema
    • XMLReader::setSchema - Validate document against XSD
    • XMLReader::XML - Set the data containing the XML to parse
    • xmlrpc_decode - 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 - End attribute
    • XMLWriter::endCdata - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDtd - End current DTD
    • XMLWriter::endDtdAttlist - End current DTD AttList
    • XMLWriter::endDtdElement - End current DTD element
    • XMLWriter::endDtdEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPi - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openUri - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNs - Create start namespaced attribute
    • XMLWriter::startCdata - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDtd - Create start DTD tag
    • XMLWriter::startDtdAttlist - Create start DTD AttList
    • XMLWriter::startDtdElement - Create start DTD element
    • XMLWriter::startDtdEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNs - Create start namespaced element tag
    • XMLWriter::startPi - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNs - Write full namespaced attribute
    • XMLWriter::writeCdata - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDtd - Write full DTD tag
    • XMLWriter::writeDtdAttlist - Write full DTD AttList tag
    • XMLWriter::writeDtdElement - Write full DTD element tag
    • XMLWriter::writeDtdEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNs - Write full namespaced element tag
    • XMLWriter::writePi - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - 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 - Get value of a parameter
    • XSLTProcessor::getSecurityPrefs - Get security preferences
    • XSLTProcessor::hasExsltSupport - Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet - Import stylesheet
    • XSLTProcessor::registerPHPFunctions - Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter - Remove parameter
    • XSLTProcessor::setParameter - Set value for a parameter
    • XSLTProcessor::setProfiling - Sets profiling output file
    • XSLTProcessor::setSecurityPrefs - Set security preferences
    • XSLTProcessor::transformToDoc - Transform to a document
    • XSLTProcessor::transformToUri - Transform to URI
    • XSLTProcessor::transformToXml - Transform to XML
    • XSLTProcessor::__construct - Creates a new XSLTProcessor object
  • y
    • Yac::add - Store into cache
    • Yac::delete - Remove items from cache
    • Yac::dump - Dump cache
    • Yac::flush - Flush the cache
    • Yac::get - Retrieve values from cache
    • Yac::info - Status of cache
    • Yac::set - Store into cache
    • Yac::__construct - Constructor
    • Yac::__get - Getter
    • Yac::__set - Setter
    • Yaconf::get - Retrieve a item
    • Yaconf::has - Determine if a item exists
    • Yaf_Action_Abstract::execute - Action entry point
    • Yaf_Action_Abstract::getController - Retrieve controller object
    • Yaf_Action_Abstract::getControllerName - Get controller name
    • Yaf_Application::app - Retrieve an Application instance
    • Yaf_Application::bootstrap - Call bootstrap
    • Yaf_Application::clearLastError - Clear the last error info
    • Yaf_Application::environ - Retrive environ
    • Yaf_Application::execute - Execute a callback
    • Yaf_Application::getAppDirectory - Get the application directory
    • Yaf_Application::getConfig - Retrive the config instance
    • Yaf_Application::getDispatcher - Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg - Get message of the last occurred error
    • Yaf_Application::getLastErrorNo - Get code of last occurred error
    • Yaf_Application::getModules - Get defined module names
    • Yaf_Application::run - Start Yaf_Application
    • Yaf_Application::setAppDirectory - Change the application directory
    • Yaf_Application::__construct - Yaf_Application constructor
    • Yaf_Application::__destruct - The __destruct purpose
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - Find a config whether readonly
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - Cast to array
    • Yaf_Config_Ini::count - Count all elements in Yaf_Config.ini
    • Yaf_Config_Ini::current - Retrieve the current value
    • Yaf_Config_Ini::key - Fetch current element's key
    • Yaf_Config_Ini::next - Advance the internal pointer
    • Yaf_Config_Ini::offsetExists - The offsetExists purpose
    • Yaf_Config_Ini::offsetGet - The offsetGet purpose
    • Yaf_Config_Ini::offsetSet - The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Ini::readonly - The readonly purpose
    • Yaf_Config_Ini::rewind - The rewind purpose
    • Yaf_Config_Ini::toArray - Return config as a PHP array
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - Yaf_Config_Ini constructor
    • Yaf_Config_Ini::__get - Retrieve a element
    • Yaf_Config_Ini::__isset - Determine if a key is exists
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - The count purpose
    • Yaf_Config_Simple::current - The current purpose
    • Yaf_Config_Simple::key - The key purpose
    • Yaf_Config_Simple::next - The next purpose
    • Yaf_Config_Simple::offsetExists - The offsetExists purpose
    • Yaf_Config_Simple::offsetGet - The offsetGet purpose
    • Yaf_Config_Simple::offsetSet - The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Simple::readonly - The readonly purpose
    • Yaf_Config_Simple::rewind - The rewind purpose
    • Yaf_Config_Simple::toArray - Returns a PHP array
    • Yaf_Config_Simple::valid - The valid purpose
    • Yaf_Config_Simple::__construct - The __construct purpose
    • Yaf_Config_Simple::__get - The __get purpose
    • Yaf_Config_Simple::__isset - The __isset purpose
    • Yaf_Config_Simple::__set - The __set purpose
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - Forward to another action
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - Get module name
    • Yaf_Controller_Abstract::getName - Get self name
    • Yaf_Controller_Abstract::getRequest - Retrieve current request object
    • Yaf_Controller_Abstract::getResponse - Retrieve current response object
    • Yaf_Controller_Abstract::getView - Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::init - Controller initializer
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - Redirect to a URL
    • Yaf_Controller_Abstract::render - Render view template
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - Switch on/off autorendering
    • Yaf_Dispatcher::catchException - Switch on/off exception catching
    • Yaf_Dispatcher::disableView - Disable view rendering
    • Yaf_Dispatcher::dispatch - Dispatch a request
    • Yaf_Dispatcher::enableView - Enable view rendering
    • Yaf_Dispatcher::flushInstantly - Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication - Retrieve the application
    • Yaf_Dispatcher::getDefaultAction - Retrive the default action name
    • Yaf_Dispatcher::getDefaultController - Retrive the default controller name
    • Yaf_Dispatcher::getDefaultModule - Retrive the default module name
    • Yaf_Dispatcher::getInstance - Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest - Retrive the request instance
    • Yaf_Dispatcher::getRouter - Retrive router instance
    • Yaf_Dispatcher::initView - Initialize view and return it
    • Yaf_Dispatcher::registerPlugin - Register a plugin
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - Set error handler
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - Set a custom view engine
    • Yaf_Dispatcher::throwException - Switch on/off exception throwing
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher constructor
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - Get the library path
    • Yaf_Loader::getLocalNamespace - Retrive all register namespaces info
    • Yaf_Loader::getNamespacePath - Retieve path of a registered namespace
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - Register local class prefix
    • Yaf_Loader::registerNamespace - Register namespace with searching path
    • Yaf_Loader::setLibraryPath - Change the library path
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - Hook before dispatch loop
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - Remove an item from registry
    • Yaf_Registry::get - Retrieve an item from registry
    • Yaf_Registry::has - Check whether an item exists
    • Yaf_Registry::set - Add an item into registry
    • Yaf_Registry::__construct - Yaf_Registry implements singleton
    • Yaf_Request_Abstract::clearParams - Remove all params
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - Retrieve ENV varialbe
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - Retrieve client's preferred language
    • Yaf_Request_Abstract::getMethod - Retrieve the request method
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - Retrieve calling parameter
    • Yaf_Request_Abstract::getParams - Retrieve all calling parameters
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - Retrieve SERVER variable
    • Yaf_Request_Abstract::isCli - Determine if request is CLI request
    • Yaf_Request_Abstract::isDispatched - Determin if the request is dispatched
    • Yaf_Request_Abstract::isGet - Determine if request is GET request
    • Yaf_Request_Abstract::isHead - Determine if request is HEAD request
    • Yaf_Request_Abstract::isOptions - Determine if request is OPTIONS request
    • Yaf_Request_Abstract::isPost - Determine if request is POST request
    • Yaf_Request_Abstract::isPut - Determine if request is PUT request
    • Yaf_Request_Abstract::isRouted - Determin if request has been routed
    • Yaf_Request_Abstract::isXmlHttpRequest - Determine if request is AJAX request
    • Yaf_Request_Abstract::setActionName - Set action name
    • Yaf_Request_Abstract::setBaseUri - Set base URI
    • Yaf_Request_Abstract::setControllerName - Set controller name
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - Set module name
    • Yaf_Request_Abstract::setParam - Set a calling parameter to a request
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - Retrieve variable from client
    • Yaf_Request_Http::getCookie - Retrieve Cookie variable
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - Retrieve POST variable
    • Yaf_Request_Http::getQuery - Fetch a query parameter
    • Yaf_Request_Http::getRaw - Retrieve Raw request body
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - Determin if request is Ajax Request
    • Yaf_Request_Http::__construct - Constructor of Yaf_Request_Http
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - Determin if request is AJAX request
    • Yaf_Request_Simple::__construct - Constructor of Yaf_Request_Simple
    • Yaf_Response_Abstract::appendBody - Append to response body
    • Yaf_Response_Abstract::clearBody - Discard all exists response body
    • Yaf_Response_Abstract::clearHeaders - Discard all set headers
    • Yaf_Response_Abstract::getBody - Retrieve a exists content
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - Send response
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - Set content to response
    • Yaf_Response_Abstract::setHeader - Set reponse header
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - Retrieve all bodys as string
    • Yaf_Router::addConfig - Add config-defined routes into Router
    • Yaf_Router::addRoute - Add new Route into Router
    • Yaf_Router::getCurrentRoute - Get the effective route name
    • Yaf_Router::getRoute - Retrieve a route by name
    • Yaf_Router::getRoutes - Retrieve registered routes
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::assemble - Assemble a request
    • Yaf_Route_Interface::route - Route a request
    • Yaf_Route_Map::assemble - Assemble a url
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::assemble - Assemble a url
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - Yaf_Route_Regex constructor
    • Yaf_Route_Rewrite::assemble - Assemble a url
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - Yaf_Route_Rewrite constructor
    • Yaf_Route_Simple::assemble - Assemble a url
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::assemble - Assemble a url
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::assemble - Assemble a url
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__construct - Constructor of Yaf_Session
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_View_Interface::assign - Assign value to View engine
    • Yaf_View_Interface::display - Render and output a template
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - Render a template
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - Assign values
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::clear - Clear Assigned values
    • Yaf_View_Simple::display - Render and display
    • Yaf_View_Simple::eval - Render template
    • Yaf_View_Simple::getScriptPath - Get templates directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempaltes directory
    • Yaf_View_Simple::__construct - Constructor of Yaf_View_Simple
    • Yaf_View_Simple::__get - Retrieve assigned variable
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - Set value to engine
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Send the YAML representation of a value to a file
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • Yar_Client::setOpt - Set calling contexts
    • Yar_Client::__call - Call service
    • Yar_Client::__construct - Create a client
    • Yar_Client_Exception::getType - Retrieve exception's type
    • Yar_Concurrent_Client::call - Register a concurrent call
    • Yar_Concurrent_Client::loop - Send all calls
    • Yar_Concurrent_Client::reset - Clean all registered calls
    • Yar_Server::handle - Start RPC Server
    • Yar_Server::__construct - Register a server
    • Yar_Server_Exception::getType - Retrieve exception's type
    • yaz_addinfo - Returns additional error information
    • yaz_ccl_conf - Configure CCL parser
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepares for a connection to a Z39.50 server
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Sets sorting criteria
    • yaz_syntax - Specifies the preferred record syntax for retrieval
    • yaz_wait - Wait for Z39.50 requests to complete
  • z
    • zend_thread_id - Returns a unique identifier for the current thread
    • zend_version - Gets the version of the current Zend engine
    • ZipArchive::addEmptyDir - Add a new directory
    • ZipArchive::addFile - Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString - Add a file to a ZIP archive using its contents
    • ZipArchive::addGlob - Add files from a directory by glob pattern
    • ZipArchive::addPattern - Add files from a directory by PCRE pattern
    • ZipArchive::clearError - Clear the status error message, system and/or zip messages
    • ZipArchive::close - Close the active archive (opened or newly created)
    • ZipArchive::count - Counts the number of files in the archive
    • ZipArchive::deleteIndex - Delete an entry in the archive using its index
    • ZipArchive::deleteName - Delete an entry in the archive using its name
    • ZipArchive::extractTo - Extract the archive contents
    • ZipArchive::getArchiveComment - Returns the Zip archive comment
    • ZipArchive::getArchiveFlag - Returns the value of a Zip archive global flag
    • ZipArchive::getCommentIndex - Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName - Returns the comment of an entry using the entry name
    • ZipArchive::getExternalAttributesIndex - Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName - Retrieve the external attributes of an entry defined by its name
    • ZipArchive::getFromIndex - Returns the entry contents using its index
    • ZipArchive::getFromName - Returns the entry contents using its name
    • ZipArchive::getNameIndex - Returns the name of an entry using its index
    • ZipArchive::getStatusString - Returns the status error message, system and/or zip messages
    • ZipArchive::getStream - Get a file handler to the entry defined by its name (read only)
    • ZipArchive::getStreamIndex - Get a file handler to the entry defined by its index (read only)
    • ZipArchive::getStreamName - Get a file handler to the entry defined by its name (read only)
    • ZipArchive::isCompressionMethodSupported - Check if a compression method is supported by libzip
    • ZipArchive::isEncryptionMethodSupported - Check if a encryption method is supported by libzip
    • ZipArchive::locateName - Returns the index of the entry in the archive
    • ZipArchive::open - Open a ZIP file archive
    • ZipArchive::registerCancelCallback - Register a callback to allow cancellation during archive close.
    • ZipArchive::registerProgressCallback - Register a callback to provide updates during archive close.
    • ZipArchive::renameIndex - Renames an entry defined by its index
    • ZipArchive::renameName - Renames an entry defined by its name
    • ZipArchive::replaceFile - Replace file in ZIP archive with a given path
    • ZipArchive::setArchiveComment - Set the comment of a ZIP archive
    • ZipArchive::setArchiveFlag - Set a global flag of a ZIP archive
    • ZipArchive::setCommentIndex - Set the comment of an entry defined by its index
    • ZipArchive::setCommentName - Set the comment of an entry defined by its name
    • ZipArchive::setCompressionIndex - Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName - Set the compression method of an entry defined by its name
    • ZipArchive::setEncryptionIndex - Set the encryption method of an entry defined by its index
    • ZipArchive::setEncryptionName - Set the encryption method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex - Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName - Set the external attributes of an entry defined by its name
    • ZipArchive::setMtimeIndex - Set the modification time of an entry defined by its index
    • ZipArchive::setMtimeName - Set the modification time of an entry defined by its name
    • ZipArchive::setPassword - Set the password for the active archive
    • ZipArchive::statIndex - Get the details of an entry defined by its index
    • ZipArchive::statName - Get the details of an entry defined by its name
    • ZipArchive::unchangeAll - Undo all changes done in the archive
    • ZipArchive::unchangeArchive - Revert all global changes done in the archive
    • ZipArchive::unchangeIndex - Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName - Revert all changes done to an entry with the given name
    • Zip context options - Zip context option listing
    • zip_close - Close a ZIP file archive
    • zip_entry_close - Close a directory entry
    • zip_entry_compressedsize - Retrieve the compressed size of a directory entry
    • zip_entry_compressionmethod - Retrieve the compression method of a directory entry
    • zip_entry_filesize - Retrieve the actual file size of a directory entry
    • zip_entry_name - Retrieve the name of a directory entry
    • zip_entry_open - Open a directory entry for reading
    • zip_entry_read - Read from an open directory entry
    • zip_open - Open a ZIP file archive
    • zip_read - Read next entry in a ZIP file archive
    • zlib:// - Compression Streams
    • Zlib context options - Zlib context option listing
    • zlib_decode - Uncompress any raw/gzip/zlib encoded data
    • zlib_encode - Compress data with the specified encoding
    • zlib_get_coding_type - Returns the coding type used for output compression
    • 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 - Attempt to load undefined class
    • __halt_compiler - Halts the compiler execution

User Contributed Notes

There are no user contributed notes for this page.


Example listing

List of all the examples in the manual

  • Example#0 - An introductory example
  • Example#1 - Our first PHP script: hello.php
  • Example#2 - Get system information from PHP
  • Example#3 - Printing a variable (Array element)
  • Example#4 - Example using control structures and functions
  • Example#5 - Mixing both HTML and PHP modes
  • Example#6 - A simple HTML form
  • Example#7 - Printing data from our form
  • Example#8 - Partial lighttpd.conf
  • Example#9 - Spawning FastCGI Responders
  • Example#10 - Connecting to remote php-fastcgi instances
  • Example#11 - OpenBSD Package Install Example
  • Example#12 - Debian Install Example with Apache 2
  • Example#13 - Stopping and starting Apache once PHP is installed
  • Example#14 - Methods for listing additional PHP packages
  • Example#15 - Install PHP with MySQL, cURL
  • Example#16 - Recommended OpCache configuration
  • Example#17 - Recommended WinCache configuration
  • Example#18 - Command line to configure IIS and PHP
  • Example#19 - Registry changes
  • Example#20 - PHP and Apache 2.x as handler
  • Example#21 - PHP and Apache 2.x as CGI
  • Example#22 - Configure Apache to run PHP as FastCGI
  • Example#23 - Passing environment variables and PHP settings to a pool
  • Example#24 - set PHP settings in nginx.conf
  • Example#25 - phpinfo call
  • Example#26 - php.ini Environment Variables
  • Example#27 - php.ini example
  • Example#28 - Apache configuration example
  • Example#29 - PHP Opening and Closing Tags
  • Example#30 - Advanced escaping using conditions
  • Example#31 - Example showing the closing tag encompassing the trailing newline
  • Example#32 - Integer literals
  • Example#33 - Integer overflow on a 32-bit system
  • Example#34 - Integer overflow on a 64-bit system
  • Example#35 - Basic Heredoc example as of PHP 7.3.0
  • Example#36 - Closing identifier must not be indented further than any lines of the body
  • Example#37 - Different indentation for body (spaces) closing identifier
  • Example#38 - Continuing an expression after a closing identifier
  • Example#39 - Closing identifier in body of the string tends to cause ParseError
  • Example#40 - Invalid example, prior to PHP 7.3.0
  • Example#41 - Valid example, even prior to PHP 7.3.0
  • Example#42 - Heredoc string quoting example
  • Example#43 - Heredoc in arguments example
  • Example#44 - Using Heredoc to initialize static values
  • Example#45 - Using double quotes in Heredoc
  • Example#46 - Nowdoc string quoting example
  • Example#47 - Nowdoc string quoting example with variables
  • Example#48 - Static data example
  • Example#49 - Simple syntax example
  • Example#50 - Negative numeric indices
  • Example#51 - Some string examples
  • Example#52 - Example of Illegal String Offsets
  • Example#53 - A simple array
  • Example#54 - Type Casting and Overwriting example
  • Example#55 - Mixed int and string keys
  • Example#56 - Indexed arrays without key
  • Example#57 - Keys not on all elements
  • Example#58 - Complex Type Casting and Overwriting example
  • Example#59 - Accessing array elements
  • Example#60 - Array dereferencing
  • Example#61 - Simple array unpacking
  • Example#62 - Array unpacking with duplicate key
  • Example#63 - Using array()
  • Example#64 - Collection
  • Example#65 - Changing element in the loop
  • Example#66 - One-based index
  • Example#67 - Filling an array
  • Example#68 - Sorting an array
  • Example#69 - Recursive and multi-dimensional arrays
  • Example#70 - Callback function examples
  • Example#71 - Callback example using a Closure
  • Example#72 - Iterable generator return type example
  • Example#73 -
  • Example#74 - Typed pass-by-reference Parameters
  • Example#75 - Old way to make arguments nullable
  • Example#76 - Basic class type declaration
  • Example#77 - Basic interface type declaration
  • Example#78 - Basic return type declaration
  • Example#79 - Returning an object
  • Example#80 - Nullable argument type declaration
  • Example#81 - Nullable return type declaration
  • Example#82 - Class property type declaration
  • Example#83 - Strict typing for arguments values
  • Example#84 - Coercive typing for argument values
  • Example#85 - Strict typing for return values
  • Example#86 - Example of types being coerced into a type part of the union
  • Example#87 - Default values of uninitialized variables
  • Example#88 - Using global
  • Example#89 - Using $GLOBALS instead of global
  • Example#90 - Example demonstrating superglobals and scope
  • Example#91 - Example demonstrating need for static variables
  • Example#92 - Example use of static variables
  • Example#93 - Static variables with recursive functions
  • Example#94 - Declaring static variables
  • Example#95 - Usage of static Variables in Inherited Methods
  • Example#96 - Variable property example
  • Example#97 - A simple HTML form
  • Example#98 - Accessing data from a simple POST HTML form
  • Example#99 - More complex form variables
  • Example#100 - A setcookie example
  • Example#101 - Valid and invalid constant names
  • Example#102 - Defining Constants
  • Example#103 - Defining Constants using the const keyword
  • Example#104 - Associativity
  • Example#105 - Undefined order of evaluation
  • Example#106 - +, - and . have the same precedence (prior to PHP 8.0.0)
  • Example#107 - PERL string increment example
  • Example#108 - Alphanumerical string converted to float
  • Example#109 - Assigning by reference
  • Example#110 - Bitwise AND, OR and XOR operations on integers
  • Example#111 - Bitwise XOR operations on strings
  • Example#112 - Bit shifting on integers
  • Example#113 - Boolean/null comparison
  • Example#114 - Transcription of standard array comparison
  • Example#115 - Assigning a default value
  • Example#116 - Non-obvious Ternary Behaviour
  • Example#117 - Short-ternary chaining
  • Example#118 - Assigning a default value
  • Example#119 - Nesting null coalescing operator
  • Example#120 - Logical operators illustrated
  • Example#121 - Comparing arrays
  • Example#122 - Using instanceof with classes
  • Example#123 - Using instanceof with inherited classes
  • Example#124 - Using instanceof to check if object is not an instanceof a class
  • Example#125 - Using instanceof with interfaces
  • Example#126 - Using instanceof with other variables
  • Example#127 - Using instanceof to test other variables
  • Example#128 - Using instanceof to test constants
  • Example#129 - Using instanceof with an arbitrary expression
  • Example#130 - switch structure
  • Example#131 - Basic match usage
  • Example#132 - Structure of a match expression
  • Example#133 - Example of an unhandled match expression
  • Example#134 - Using a generalized match expressions to branch on integer ranges
  • Example#135 - Using a generalized match expressions to branch on string content
  • Example#136 - Tick usage example
  • Example#137 - Declaring an encoding for the script.
  • Example#138 - Basic include example
  • Example#139 - Including within functions
  • Example#140 - include through HTTP
  • Example#141 - Comparing return value of include
  • Example#142 - include and the return statement
  • Example#143 - Using output buffering to include a PHP file into a string
  • Example#144 - goto example
  • Example#145 - goto loop example
  • Example#146 - This will not work
  • Example#147 - Pseudo code to demonstrate function uses
  • Example#148 - Conditional functions
  • Example#149 - Functions within functions
  • Example#150 - Recursive functions
  • Example#151 - Passing arrays to functions
  • Example#152 - Function Argument List with trailing Comma
  • Example#153 - Passing function parameters by reference
  • Example#154 - Use of default parameters in functions
  • Example#155 - Using non-scalar types as default values
  • Example#156 - Using objects as default values (as of PHP 8.1.0)
  • Example#157 - Incorrect usage of default function arguments
  • Example#158 - Correct usage of default function arguments
  • Example#159 - Correct usage of default function arguments
  • Example#160 - Declaring optional arguments after mandatory arguments
  • Example#161 - Using ... to access variable arguments
  • Example#162 - Using ... to provide arguments
  • Example#163 - Type declared variable arguments
  • Example#164 - Named argument syntax
  • Example#165 - Positional arguments versus named arguments
  • Example#166 - Same example as above with a different order of parameters
  • Example#167 - Combining named arguments with positional arguments
  • Example#168 - Error thrown when passing the same parameter multiple times
  • Example#169 - Use named arguments after unpacking
  • Example#170 - Use of return
  • Example#171 - Returning an array to get multiple values
  • Example#172 - Returning a reference from a function
  • Example#173 - Variable function example
  • Example#174 - Variable method example
  • Example#175 - Variable method example with static properties
  • Example#176 - Complex callables
  • Example#177 -
  • Example#178 - Anonymous function example
  • Example#179 - Anonymous function variable assignment example
  • Example#180 - Inheriting variables from the parent scope
  • Example#181 - Closures and scoping
  • Example#182 - Automatic binding of $this
  • Example#183 - Attempting to use $this inside a static anonymous function
  • Example#184 - Attempting to bind an object to a static anonymous function
  • Example#185 - Arrow functions capture variables by value automatically
  • Example#186 - Arrow functions capture variables by value automatically, even when nested
  • Example#187 - Examples of arrow functions
  • Example#188 - Values from the outer scope cannot be modified by arrow functions
  • Example#189 - Simple first class callable syntax
  • Example#190 - Scope comparison of CallableExpr(...) and traditional callable
  • Example#191 -
  • Example#192 - Simple Class definition
  • Example#193 - Some examples of the $this pseudo-variable
  • Example#194 -
  • Example#195 -
  • Example#196 - Creating an instance
  • Example#197 - Creating an instance using an arbitrary expression
  • Example#198 - Object Assignment
  • Example#199 - Creating new objects
  • Example#200 - Access member of newly created object
  • Example#201 - Property access vs. method call
  • Example#202 - Calling an anonymous function stored in a property
  • Example#203 - Simple Class Inheritance
  • Example#204 - Compatible child methods
  • Example#205 - Fatal error when a child method removes a parameter
  • Example#206 - Fatal error when a child method makes an optional parameter mandatory
  • Example#207 - Error when using named arguments and parameters were renamed in a child class
  • Example#208 - Class name resolution
  • Example#209 - Missing class name resolution
  • Example#210 - Object name resolution
  • Example#211 - Nullsafe Operator
  • Example#212 - Property declarations
  • Example#213 - Example of typed properties
  • Example#214 - Accessing properties
  • Example#215 - Example of readonly properties
  • Example#216 - Illegal initialization of readonly properties
  • Example#217 -
  • Example#218 -
  • Example#219 -
  • Example#220 - Defining and using a constant
  • Example#221 - Namespaced ::class example
  • Example#222 - Class constant expression example
  • Example#223 - Class constant visibility modifiers, as of PHP 7.1.0
  • Example#224 - Autoload example
  • Example#225 - Autoload other example
  • Example#226 - Constructors in inheritance
  • Example#227 - Using constructor arguments
  • Example#228 - Using constructor property promotion
  • Example#229 - Using new in initializers
  • Example#230 - Using static creation methods
  • Example#231 - Destructor Example
  • Example#232 - Property declaration
  • Example#233 - Method Declaration
  • Example#234 - Constant Declaration as of PHP 7.1.0
  • Example#235 - Accessing private members of the same object type
  • Example#236 -
  • Example#237 - Inheritance Example
  • Example#238 - The overriding method does not declare any return type
  • Example#239 - The overriding method declares a wrong return type
  • Example#240 - The overriding method declares a wrong return type without a deprecation notice
  • Example#241 - :: from outside the class definition
  • Example#242 - :: from inside the class definition
  • Example#243 - Calling a parent's method
  • Example#244 - Static method example
  • Example#245 - Static property example
  • Example#246 - Abstract class example
  • Example#247 - Abstract class example
  • Example#248 - Interface example
  • Example#249 - Extendable Interfaces
  • Example#250 - Variance compatibility with multiple interfaces
  • Example#251 - Multiple interface inheritance
  • Example#252 - Interfaces with constants
  • Example#253 - Interfaces with abstract classes
  • Example#254 - Extending and implementing simultaneously
  • Example#255 - Trait example
  • Example#256 - Precedence Order Example
  • Example#257 - Alternate Precedence Order Example
  • Example#258 - Multiple Traits Usage
  • Example#259 - Conflict Resolution
  • Example#260 - Changing Method Visibility
  • Example#261 - Traits Composed from Traits
  • Example#262 - Express Requirements by Abstract Methods
  • Example#263 - Static Variables
  • Example#264 - Static Methods
  • Example#265 - Static Properties
  • Example#266 - Defining Properties
  • Example#267 - Conflict Resolution
  • Example#268 - Defining Constants
  • Example#269 - Conflict Resolution
  • Example#270 - Overloading properties via the __get(), __set(), __isset() and __unset() methods
  • Example#271 - Overloading methods via the __call() and __callStatic() methods
  • Example#272 - Simple Object Iteration
  • Example#273 - Sleep and wakeup
  • Example#274 - Serialize and unserialize
  • Example#275 - Simple example
  • Example#276 - Using __invoke()
  • Example#277 - Using __invoke()
  • Example#278 - Using __set_state()
  • Example#279 - Using __debugInfo()
  • Example#280 - Final methods example
  • Example#281 - Final class example
  • Example#282 - Final constants example as of PHP 8.1.0
  • Example#283 - Cloning an object
  • Example#284 - Access member of freshly cloned object
  • Example#285 - Example of object comparison
  • Example#286 - self:: usage
  • Example#287 - static:: simple usage
  • Example#288 - static:: usage in a non-static context
  • Example#289 - Forwarding and non-forwarding calls
  • Example#290 - References and Objects
  • Example#291 - Namespace syntax example
  • Example#292 - Declaring a single namespace
  • Example#293 - Declaring a single namespace
  • Example#294 - Declaring a single namespace with hierarchy
  • Example#295 - Declaring multiple namespaces, simple combination syntax
  • Example#296 - Declaring multiple namespaces, bracketed syntax
  • Example#297 - Declaring multiple namespaces and unnamespaced code
  • Example#298 - Declaring multiple namespaces and unnamespaced code
  • Example#299 - Accessing global classes, functions and constants from within a namespace
  • Example#300 - Dynamically accessing elements
  • Example#301 - Dynamically accessing namespaced elements
  • Example#302 - __NAMESPACE__ example, namespaced code
  • Example#303 - __NAMESPACE__ example, global code
  • Example#304 - using __NAMESPACE__ for dynamic name construction
  • Example#305 - the namespace operator, inside a namespace
  • Example#306 - the namespace operator, in global code
  • Example#307 - importing/aliasing with the use operator
  • Example#308 - importing/aliasing with the use operator, multiple use statements combined
  • Example#309 - Importing and dynamic names
  • Example#310 - Importing and fully qualified names
  • Example#311 - Illegal importing rule
  • Example#312 - Using global space specification
  • Example#313 - Accessing global classes inside a namespace
  • Example#314 - global functions/constants fallback inside a namespace
  • Example#315 - Name resolutions illustrated
  • Example#316 - Accessing global classes outside a namespace
  • Example#317 - Accessing global classes outside a namespace
  • Example#318 - Accessing internal classes in namespaces
  • Example#319 - Accessing internal classes, functions or constants in namespaces
  • Example#320 - Fully Qualified names
  • Example#321 - Qualified names
  • Example#322 - Unqualified class names
  • Example#323 - Unqualified function or constant names
  • Example#324 - Dangers of using namespaced names inside a double-quoted string
  • Example#325 - Undefined constants
  • Example#326 - Undefined constants
  • Example#327 - Basic limited values
  • Example#328 - Advanced exclusive values
  • Example#329 - Converting error reporting to exceptions
  • Example#330 - Throwing an Exception
  • Example#331 - Exception handling with a finally block
  • Example#332 - Interaction between the finally block and return
  • Example#333 - Nested Exception
  • Example#334 - Multi catch exception handling
  • Example#335 - Omitting the caught variable
  • Example#336 - Throw as an expression
  • Example#337 - The Built in Exception class
  • Example#338 - Extending the Exception class
  • Example#339 - Basic usage
  • Example#340 - Implementing range as a generator
  • Example#341 - A simple example of yielding values
  • Example#342 - Yielding a key/value pair
  • Example#343 - Yielding nulls
  • Example#344 - Yielding values by reference
  • Example#345 - yield from with iterator_to_array
  • Example#346 - Basic use of yield from
  • Example#347 - yield from and return values
  • Example#348 - Implementing optional methods of an interface with Attributes
  • Example#349 - Attribute Syntax
  • Example#350 - Reading Attributes using Reflection API
  • Example#351 - Reading Specific Attributes using Reflection API
  • Example#352 - Simple Attribute Class
  • Example#353 - Using target specification to restrict where attributes can be used
  • Example#354 - Using IS_REPEATABLE to allow attribute on a declaration multiple times
  • Example#355 - Using references with undefined variables
  • Example#356 - Referencing global variables inside functions
  • Example#357 - References and foreach statement
  • Example#358 - $GLOBALS example
  • Example#359 - writing entire $GLOBALS will result in error.
  • Example#360 - $_SERVER example
  • Example#361 - $_GET example
  • Example#362 - $_POST example
  • Example#363 - $_ENV example
  • Example#364 - $_COOKIE example
  • Example#365 - $php_errormsg example
  • Example#366 - $http_response_header example
  • Example#367 - $argc example
  • Example#368 - $argv example
  • Example#369 - Exception::getMessage example
  • Example#370 - Exception::getPrevious example
  • Example#371 - Exception::getCode example
  • Example#372 - Exception::getFile example
  • Example#373 - Exception::getLine example
  • Example#374 - Exception::getTrace example
  • Example#375 - Exception::getTraceAsString example
  • Example#376 - Exception::__toString example
  • Example#377 - Use set_error_handler to change error messages into ErrorException.
  • Example#378 - ErrorException::getSeverity example
  • Example#379 - Error::getMessage example
  • Example#380 - Error::getPrevious example
  • Example#381 - Error::getCode example
  • Example#382 - Error::getFile example
  • Example#383 - Error::getLine example
  • Example#384 - Error::getTrace example
  • Example#385 - Error::getTraceAsString example
  • Example#386 - Error::__toString example
  • Example#387 - Basic usage
  • Example#388 - Basic usage
  • Example#389 - Basic usage
  • Example#390 - ArrayAccess::offsetExists example
  • Example#391 - Basic usage
  • Example#392 - Closure::bind example
  • Example#393 - Closure::bindTo example
  • Example#394 - Closure::call example
  • Example#395 - Created as a result of typecasting to object
  • Example#396 - Created as a result of json_decode
  • Example#397 - Declaring dynamic properties
  • Example#398 - Generator::getReturn example
  • Example#399 - Generator::key example
  • Example#400 - Using Generator::send to inject values
  • Example#401 - Throwing an exception into a generator
  • Example#402 - Basic WeakReference Usage
  • Example#403 - Weakmap usage example
  • Example#404 - Basic Stringable Usage
  • Example#405 - Basic usage
  • Example#406 - Basic usage
  • Example#407 - Basic usage
  • Example#408 - Passing a SensitiveParameterValue object to var_dump
  • Example#409 - SensitiveParameterValue::getValue example
  • Example#410 -
  • Example#411 -
  • Example#412 - Basic bindto usage example
  • Example#413 - Fetch a page and send POST data
  • Example#414 - Ignore redirects but fetch headers and content
  • Example#415 - Basic password usage example
  • Example#416 - Detecting which URL we ended up on after redirects
  • Example#417 - php://temp/maxmemory
  • Example#418 - php://filter/resource=<stream to be filtered>
  • Example#419 - php://filter/read=<filter list to apply to read chain>
  • Example#420 - php://filter/write=<filter list to apply to write chain>
  • Example#421 - php://memory and php://temp are not reusable
  • Example#422 - Print data:// contents
  • Example#423 - Fetch the media type
  • Example#424 - Basic usage
  • Example#425 - Opening a stream from an active connection
  • Example#426 - This $session variable must be kept available!
  • Example#427 - Traversing a RAR archive
  • Example#428 - Opening an encrypted file (header encryption)
  • Example#429 - Poor variable checking leads to....
  • Example#430 - ... A filesystem attack
  • Example#431 - More secure file name checking
  • Example#432 - More secure file name checking
  • Example#433 - Script vulnerable to null bytes
  • Example#434 - Correctly validating the input
  • Example#435 - Hashing password field
  • Example#436 - Splitting the result set into pages ... and making superusers (PostgreSQL)
  • Example#437 - Listing out articles ... and some passwords (any database server)
  • Example#438 - From resetting a password ... to gaining more privileges (any database server)
  • Example#439 - Attacking the database host operating system (MSSQL Server)
  • Example#440 - Avoiding SQL injection by using PDO prepared statements
  • Example#441 - Attacking Variables with a custom HTML page
  • Example#442 - Exploiting common debugging variables
  • Example#443 - Finding dangerous variables with E_ALL
  • Example#444 - Dangerous Variable Usage
  • Example#445 - Hiding PHP as another language
  • Example#446 - Using unknown types for PHP extensions
  • Example#447 - Using HTML types for PHP extensions
  • Example#448 - Basic HTTP Authentication example
  • Example#449 - Digest HTTP Authentication example
  • Example#450 - HTTP Authentication example forcing a new name/password
  • Example#451 - A simple XForms search form
  • Example#452 - Using an XForm to populate $_POST
  • Example#453 - File Upload Form
  • Example#454 - Validating file uploads
  • Example#455 - Uploading array of files
  • Example#456 - Uploading multiple files
  • Example#457 - Uploading an entire directory
  • Example#458 - Saving HTTP PUT files
  • Example#459 - Getting the title of a remote page
  • Example#460 - Storing data on a remote server
  • Example#461 - Example showing the difference to the CGI SAPI:
  • Example#462 -
  • Example#463 - Printing built in (and loaded) PHP and Zend modules
  • Example#464 - Getting a syntax error when using double quotes
  • Example#465 - Using single quotes to prevent the shell's variable substitution
  • Example#466 - Using the -B, -R and -E options to count the number of lines of a project.
  • Example#467 - Using -v to get the SAPI name and the version of PHP and Zend
  • Example#468 - --ini example
  • Example#469 - basic --rf usage
  • Example#470 - --rc example
  • Example#471 - --re example
  • Example#472 - --ri example
  • Example#473 - Execute PHP script as shell script
  • Example#474 - Script intended to be run from command line (script.php)
  • Example#475 - Batch file to run a command line PHP script (script.bat)
  • Example#476 - Executing code using the interactive shell
  • Example#477 - Tab completion
  • Example#478 - Setting php.ini settings in the interactive shell
  • Example#479 - Starting the web server
  • Example#480 - Starting with a specific document root directory
  • Example#481 - Using a Router Script
  • Example#482 - Checking for CLI Web Server Use
  • Example#483 - Handling Unsupported File Types
  • Example#484 - Accessing the CLI Web Server From Remote Machines
  • Example#485 - Creating a new zval container
  • Example#486 - Displaying zval information
  • Example#487 - Increasing refcount of a zval
  • Example#488 - Decreasing zval refcount
  • Example#489 - Creating a array zval
  • Example#490 - Adding already existing element to an array
  • Example#491 - Removing an element from an array
  • Example#492 - Adding the array itself as an element of it self
  • Example#493 - Unsetting $a
  • Example#494 - Memory usage example
  • Example#495 - GC performance influences
  • Example#496 - Running the above script
  • Example#497 - Recompiling PHP to enable GC benchmarking
  • Example#498 - GC statistics
  • Example#499 - all_probes.d for tracing all PHP Static Probes with DTrace
  • Example#500 - all_probes.stp for tracing all PHP Static Probes with SystemTap
  • Example#501 - A apcu_add example
  • Example#502 - A apcu_cache_info example
  • Example#503 - apcu_cas example
  • Example#504 - apcu_dec example
  • Example#505 - A apcu_delete example
  • Example#506 - An apcu_entry example
  • Example#507 - apcu_exists example
  • Example#508 - A apcu_fetch example
  • Example#509 - apcu_inc example
  • Example#510 - A apcu_key_info example
  • Example#511 - A apcu_sma_info example
  • Example#512 - A apcu_store example
  • Example#513 - A APCUIterator::__construct example
  • Example#514 - Using error handling in a script
  • Example#515 - debug_backtrace example
  • Example#516 - debug_print_backtrace example
  • Example#517 - An error_clear_last example
  • Example#518 - An error_get_last example
  • Example#519 - error_log examples
  • Example#520 - error_reporting examples
  • Example#521 - restore_error_handler example
  • Example#522 - restore_exception_handler example
  • Example#523 - Error handling with set_error_handler and trigger_error
  • Example#524 - set_exception_handler example
  • Example#525 - trigger_error example
  • Example#526 - Calling a function from shared library
  • Example#527 - Calling a function, returning a structure through an argument
  • Example#528 - Accessing existing C variables
  • Example#529 - Creating and Modifying C variables
  • Example#530 - Working with C arrays
  • Example#531 - Working with C enums
  • Example#532 -
  • Example#533 -
  • Example#534 - Output Control example
  • Example#535 - Output rewrite example
  • Example#536 - ob_end_clean example
  • Example#537 - ob_end_flush example
  • Example#538 - A simple ob_get_clean example
  • Example#539 - A simple ob_get_contents example
  • Example#540 - ob_get_flush example
  • Example#541 - A simple ob_get_length example
  • Example#542 - ob_gzhandler example
  • Example#543 - ob_list_handlers example
  • Example#544 - User defined callback function example
  • Example#545 - Creating an unerasable output buffer
  • Example#546 - output_add_rewrite_var example
  • Example#547 - output_reset_rewrite_vars example
  • Example#548 - assert_options example
  • Example#549 - assert example
  • Example#550 - Using a custom message
  • Example#551 - Using a custom exception class
  • Example#552 - cli_get_process_title example
  • Example#553 - cli_set_process_title example
  • Example#554 - dl examples
  • Example#555 - extension_loaded example
  • Example#556 - A gc_enabled example
  • Example#557 - gc_status Usage
  • Example#558 - get_current_user example
  • Example#559 - get_defined_constants Example
  • Example#560 - Prints the XML functions
  • Example#561 - get_include_path example
  • Example#562 - get_included_files example
  • Example#563 - get_loaded_extensions Example
  • Example#564 - Unfiltered get_resources
  • Example#565 - Filtered get_resources
  • Example#566 - getenv Example
  • Example#567 - getlastmod example
  • Example#568 - getopt example: The basics
  • Example#569 - getopt example: Introducing long options
  • Example#570 - getopt example: Passing multiple options as one
  • Example#571 - getopt example: Using rest_index
  • Example#572 - getrusage example
  • Example#573 - ini_get_all examples
  • Example#574 - Disabling details
  • Example#575 - A few ini_get examples
  • Example#576 - A few ini_parse_quantity examples
  • Example#577 - ini_restore example
  • Example#578 - Setting an ini option
  • Example#579 - A memory_get_usage example
  • Example#580 - memory_reset_peak_usage example
  • Example#581 - php_ini_loaded_file example
  • Example#582 - A simple example to list the returned ini files
  • Example#583 - php_sapi_name example
  • Example#584 - Some php_uname examples
  • Example#585 - A few OS related constant examples
  • Example#586 - Prints the general credits
  • Example#587 - Prints the core developers and the documentation group
  • Example#588 - Printing all the credits
  • Example#589 - phpinfo Example
  • Example#590 - phpversion example
  • Example#591 - PHP_VERSION_ID example and usage
  • Example#592 - Setting an environment variable
  • Example#593 - restore_include_path example
  • Example#594 - set_include_path example
  • Example#595 - Adding to the include path
  • Example#596 - sys_get_temp_dir example
  • Example#597 - version_compare examples
  • Example#598 - zend_thread_id example
  • Example#599 - zend_version example
  • Example#600 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#601 - A runkit7_function_add example
  • Example#602 - A runkit7_function_copy example
  • Example#603 - A runkit7_function_redefine example
  • Example#604 - runkit7_method_add example
  • Example#605 - runkit7_method_copy example
  • Example#606 - runkit7_method_redefine example
  • Example#607 - runkit7_method_remove example
  • Example#608 - runkit7_method_rename example
  • Example#609 - runkit7_zval_inspect example
  • Example#610 - Basic uopz_add_function Usage
  • Example#611 - uopz_allow_exit example
  • Example#612 - uopz_backup example
  • Example#613 - uopz_compose example
  • Example#614 - uopz_copy example
  • Example#615 - Basic uopz_del_function Usage
  • Example#616 - uopz_delete example
  • Example#617 - uopz_delete class example
  • Example#618 - uopz_extend example
  • Example#619 - uopz_flags example
  • Example#620 - "Unfinalize" a Class
  • Example#621 - uopz_function example
  • Example#622 - uopz_function class example
  • Example#623 - uopz_get_exit_status example
  • Example#624 - Basic uopz_get_hook Usage
  • Example#625 - uopz_get_mock example
  • Example#626 - Basic uopz_get_property Usage
  • Example#627 - uopz_get_return example
  • Example#628 - Basic uopz_get_static Usage
  • Example#629 - uopz_implement example
  • Example#630 - uopz_overload example
  • Example#631 - uopz_redefine example
  • Example#632 - uopz_rename example
  • Example#633 - uopz_rename class example
  • Example#634 - uopz_restore example
  • Example#635 - Basic uopz_set_hook Usage
  • Example#636 - uopz_set_mock example
  • Example#637 - uopz_set_mock example
  • Example#638 - uopz_set_mock and static members
  • Example#639 - Basic uopz_set_property Usage
  • Example#640 - uopz_set_return example
  • Example#641 - uopz_set_return example
  • Example#642 - uopz_set_return class example
  • Example#643 - Basic uopz_set_static Usage
  • Example#644 - uopz_undefine example
  • Example#645 - Basic uopz_unset_hook Usage
  • Example#646 - uopz_unset_mock example
  • Example#647 - uopz_unset_return example
  • Example#648 - wincache.ignorelist example
  • Example#649 - Authentication configuration for wincache.php
  • Example#650 - Enabling WinCache session handler
  • Example#651 - Enabling WinCache functions reroutes
  • Example#652 - Reroute.ini file content
  • Example#653 - A wincache_fcache_fileinfo example
  • Example#654 - A wincache_fcache_meminfo example
  • Example#655 - Using wincache_lock
  • Example#656 - A wincache_ocache_fileinfo example
  • Example#657 - A wincache_ocache_meminfo example
  • Example#658 - A wincache_refresh_if_changed example
  • Example#659 - A wincache_rplist_fileinfo example
  • Example#660 - A wincache_rplist_meminfo example
  • Example#661 - A wincache_scache_info example
  • Example#662 - A wincache_scache_meminfo example
  • Example#663 - wincache_ucache_add with key as a string
  • Example#664 - wincache_ucache_add with key as an array
  • Example#665 - Using wincache_ucache_cas
  • Example#666 - using wincache_ucache_clear
  • Example#667 - Using wincache_ucache_dec
  • Example#668 - Using wincache_ucache_delete with key as a string
  • Example#669 - Usingwincache_ucache_delete with key as an array
  • Example#670 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#671 - Using wincache_ucache_exists
  • Example#672 - wincache_ucache_get with key as a string
  • Example#673 - wincache_ucache_get with key as an array
  • Example#674 - Using wincache_ucache_inc
  • Example#675 - Using wincache_ucache_info
  • Example#676 - A wincache_ucache_meminfo example
  • Example#677 - wincache_ucache_set with key as a string
  • Example#678 - wincache_ucache_set with key as an array
  • Example#679 - Using wincache_unlock
  • Example#680 - Xhprof example with the optional GUI
  • Example#681 - xhprof_disable example
  • Example#682 - xhprof_enable examples
  • Example#683 - xhprof_sample_disable example
  • Example#684 - Make sure the item is stored
  • Example#685 - Using CHAP passwords
  • Example#686 - radius_acct_open example
  • Example#687 - radius_add_server example
  • Example#688 - radius_auth_open example
  • Example#689 - radius_create_request example
  • Example#690 - radius_cvt_addr example
  • Example#691 - radius_cvt_int example
  • Example#692 - radius_cvt_string example
  • Example#693 - radius_get_attr example
  • Example#694 - radius_get_tagged_attr_data example
  • Example#695 - radius_get_tagged_attr_tag example
  • Example#696 - radius_get_vendor_attr example
  • Example#697 - radius_put_attr example
  • Example#698 - radius_put_int example
  • Example#699 - radius_put_string example
  • Example#700 - radius_put_vendor_attr example
  • Example#701 - Readline Callback Interface Example
  • Example#702 - readline Example
  • Example#703 - Small bzip2 Example
  • Example#704 - Compressing data
  • Example#705 - Decompressing a String
  • Example#706 - bzerror example
  • Example#707 - bzopen example
  • Example#708 - bzread example
  • Example#709 - bzwrite example
  • Example#710 - Using an external file
  • Example#711 - Using a file within a phar archive
  • Example#712 - Converting a phar archive from phar to tar file format
  • Example#713 - phar.cache_list usage example
  • Example#714 - A Phar::addEmptyDir example
  • Example#715 - A Phar::addFile example
  • Example#716 - A Phar::addFromString example
  • Example#717 - A Phar::apiVersion example
  • Example#718 - A Phar::buildFromDirectory example
  • Example#719 - A Phar::buildFromIterator with SplFileInfo
  • Example#720 - A Phar::buildFromIterator with other iterators
  • Example#721 - A Phar::canCompress example
  • Example#722 - A Phar::canWrite example
  • Example#723 - A Phar::compress example
  • Example#724 - A Phar::compressFiles example
  • Example#725 - A Phar::__construct example
  • Example#726 - A Phar::convertToData example
  • Example#727 - A Phar::convertToExecutable example
  • Example#728 - A Phar::copy example
  • Example#729 - A Phar::count example
  • Example#730 - A Phar::createDefaultStub example
  • Example#731 - A Phar::decompress example
  • Example#732 - A Phar::decompressFiles example
  • Example#733 - A Phar::delMetaData example
  • Example#734 - A Phar::delete example
  • Example#735 - A Phar::extractTo example
  • Example#736 - A Phar::getMetadata example
  • Example#737 - A Phar::getStub example
  • Example#738 - A Phar::hasMetadata example
  • Example#739 - A Phar::interceptFileFuncs example
  • Example#740 - A Phar::interceptFileFuncs example
  • Example#741 - A Phar::isBuffering example
  • Example#742 - A Phar::isCompressed example
  • Example#743 - A Phar::loadPhar example
  • Example#744 - A Phar::mapPhar example
  • Example#745 - A Phar::mount example
  • Example#746 - A Phar::mungServer example
  • Example#747 - A Phar::offsetExists example
  • Example#748 - Phar::offsetGet example
  • Example#749 - A Phar::offsetSet example
  • Example#750 - A Phar::offsetUnset example
  • Example#751 - A Phar::running example
  • Example#752 - A Phar::setAlias example
  • Example#753 - A Phar::setDefaultStub example
  • Example#754 - A Phar::setMetadata example
  • Example#755 - A Phar::setStub example
  • Example#756 - A Phar::startBuffering example
  • Example#757 - A Phar::stopBuffering example
  • Example#758 - A Phar::unlinkArchive example
  • Example#759 - A Phar::webPhar example
  • Example#760 - A PharData::addEmptyDir example
  • Example#761 - A PharData::addFile example
  • Example#762 - A PharData::addFromString example
  • Example#763 - A PharData::buildFromDirectory example
  • Example#764 - A PharData::buildFromIterator with SplFileInfo
  • Example#765 - A PharData::buildFromIterator with other iterators
  • Example#766 - A PharData::compress example
  • Example#767 - A PharData::compressFiles example
  • Example#768 - A PharData::__construct example
  • Example#769 - A PharData::convertToData example
  • Example#770 - A PharData::convertToExecutable example
  • Example#771 - A PharData::copy example
  • Example#772 - A PharData::decompress example
  • Example#773 - A PharData::decompressFiles example
  • Example#774 - A PharData::delMetaData example
  • Example#775 - A PharData::delete example
  • Example#776 - A PharData::extractTo example
  • Example#777 - A PharData::offsetSet example
  • Example#778 - A PharData::offsetUnset example
  • Example#779 - A Phar::setMetadata example
  • Example#780 - A PharFileInfo::chmod example
  • Example#781 - A PharFileInfo::compress example
  • Example#782 - A PharFileInfo::__construct example
  • Example#783 - A PharFileInfo::decompress example
  • Example#784 - A PharFileInfo::delMetaData example
  • Example#785 - A PharFileInfo::getCRC32 example
  • Example#786 - A PharFileInfo::getCompressedSize example
  • Example#787 - A PharFileInfo::getMetadata example
  • Example#788 - A PharFileInfo::getPharFlags example
  • Example#789 - A PharFileInfo::isCRCChecked example
  • Example#790 - A PharFileInfo::isCompressed example
  • Example#791 - A PharFileInfo::setMetadata example
  • Example#792 - Rar installation
  • Example#793 - On-the-fly decompression
  • Example#794 - RAR extension filesystem extraction example
  • Example#795 - Object-oriented style
  • Example#796 - Procedural style
  • Example#797 - Object-oriented style
  • Example#798 - Procedural style
  • Example#799 - Object-oriented style
  • Example#800 - Procedural style
  • Example#801 - Object-oriented style
  • Example#802 - Procedural style
  • Example#803 - Object-oriented style
  • Example#804 - Procedural style
  • Example#805 - Object-oriented style
  • Example#806 - Procedural style
  • Example#807 - Object-oriented style
  • Example#808 - Procedural style
  • Example#809 - Volume Callback
  • Example#810 - Object-oriented style
  • Example#811 - Procedural style
  • Example#812 - RarArchive::__toString example
  • Example#813 - RarEntry::extract example
  • Example#814 - How to extract all files in archive:
  • Example#815 - RarEntry::getAttr example
  • Example#816 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#817 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#818 - RarEntry::getMethod example
  • Example#819 - RarEntry::getName example
  • Example#820 - RarEntry::getPackedSize example
  • Example#821 - RarEntry::getStream example
  • Example#822 - RarEntry::getUnpackedSize example
  • Example#823 - RarEntry::getVersion example
  • Example#824 - RarException::isUsingExceptions example
  • Example#825 - RarException::setUsingExceptions example
  • Example#826 - Create a Zip archive
  • Example#827 - Dump the archive details and listing
  • Example#828 - Zip stream wrapper, read an OpenOffice meta info
  • Example#829 - Zip Usage Example
  • Example#830 - Create a new directory in an archive
  • Example#831 - Open and add
  • Example#832 - Add an entry to a new archive
  • Example#833 - Add file to a directory inside an archive
  • Example#834 - ZipArchive::addGlob example
  • Example#835 - ZipArchive::addPattern example
  • Example#836 - Delete file from archive using its index
  • Example#837 - Deleting a file and directory from an archive, using names
  • Example#838 - Extract all entries
  • Example#839 - Extract two entries
  • Example#840 - Dump an archive comment
  • Example#841 - Test if archive is a torrentzip format
  • Example#842 - Dump an entry comment
  • Example#843 - Dump an entry comment
  • Example#844 - Extract all entries with Unix rights
  • Example#845 - Get the file contents
  • Example#846 - Get the file contents
  • Example#847 - Convert an image from a zip entry
  • Example#848 - ZipArchive::getNameIndex example
  • Example#849 - Get the entry contents with fread and store it
  • Example#850 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#851 - Stream wrapper and image, can be used with the xml function as well
  • Example#852 - Get the entry contents with fread and store it
  • Example#853 - Get the entry contents with fread and store it
  • Example#854 - Create an archive and then use it with ZipArchive::locateName
  • Example#855 - Open and extract
  • Example#856 - Create an archive
  • Example#857 - Create an temporary archive
  • Example#858 - Archive a file
  • Example#859 - Archive a file
  • Example#860 - Rename one entry
  • Example#861 - Rename one entry
  • Example#862 - Open and replace
  • Example#863 - Create an archive and set a comment
  • Example#864 - Create a torrentzip archive
  • Example#865 - Open an archive and set a comment for an entry
  • Example#866 - Open an archive and set a comment for an entry
  • Example#867 - Add files with different compression methods to an archive
  • Example#868 - Add files with different compression methods to an archive
  • Example#869 - Add file and set compression method
  • Example#870 - Archive and encrypt a file
  • Example#871 - Archive a file, with its Unix rights
  • Example#872 - Archive a file
  • Example#873 - Archive a file
  • Example#874 - Dump the stat info of an entry
  • Example#875 - Dump the stat info of an entry
  • Example#876 - Small Zlib Example
  • Example#877 - Working with the incremental compression and decompression API
  • Example#878 - gzclose example
  • Example#879 - gzcompress example
  • Example#880 - gzdeflate example
  • Example#881 - Creating a gzip file
  • Example#882 - gzeof example
  • Example#883 - gzfile example
  • Example#884 - gzgetc example
  • Example#885 - gzgets example
  • Example#886 - gzgetss example
  • Example#887 - gzinflate example
  • Example#888 - gzopen Example
  • Example#889 - gzpassthru example
  • Example#890 - gzread example
  • Example#891 - gzseek example
  • Example#892 - gzuncompress example
  • Example#893 - gzwrite example
  • Example#894 - zlib_encode example
  • Example#895 - hash_algos example
  • Example#896 - hash_copy example
  • Example#897 - hash_equals example
  • Example#898 - Using hash_file
  • Example#899 - hash_hkdf example
  • Example#900 - hash_hmac_algos example
  • Example#901 - hash_hmac_file example
  • Example#902 - hash_hmac example
  • Example#903 - Incremental hashing example
  • Example#904 - hash_pbkdf2 example, basic usage
  • Example#905 - hash_update_stream example
  • Example#906 - A hash example
  • Example#907 - mcrypt_create_iv Example
  • Example#908 - mcrypt_enc_get_algorithms_name example
  • Example#909 - mcrypt_enc_get_modes_name example
  • Example#910 - mcrypt_enc_get_supported_key_sizes example
  • Example#911 - mcrypt_encrypt Example
  • Example#912 - mcrypt_get_block_size example
  • Example#913 - mcrypt_get_cipher_name Example
  • Example#914 - mcrypt_get_iv_size Example
  • Example#915 - mcrypt_get_key_size Example
  • Example#916 - mcrypt_list_algorithms Example
  • Example#917 - mcrypt_list_modes Example
  • Example#918 - mcrypt_module_open Examples
  • Example#919 - Using mcrypt_module_open in encryption
  • Example#920 - mcrypt_module_self_test example
  • Example#921 - mdecrypt_generic Example
  • Example#922 - Computes the MD5 digest and hmac and print it out as hex
  • Example#923 - Traversing all hashes
  • Example#924 - mhash_get_block_size Example
  • Example#925 - mhash_get_hash_name Example
  • Example#926 - openssl_cipher_iv_length example
  • Example#927 - openssl_cipher_key_length example
  • Example#928 - openssl_cms_sign example
  • Example#929 - openssl_csr_export_to_file() example
  • Example#930 - openssl_csr_export() example
  • Example#931 - openssl_csr_get_public_key() example
  • Example#932 - openssl_csr_get_subject() example
  • Example#933 - Creating a self-signed certificate
  • Example#934 - Creating a self-signed ECC certificate (as of PHP 7.1.0)
  • Example#935 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#936 - Compute a shared secret
  • Example#937 - Generate a DH public/private keypair in php
  • Example#938 - AES Authenticated Encryption in GCM mode example for PHP 7.1+
  • Example#939 - AES Authenticated Encryption example prior to PHP 7.1
  • Example#940 - openssl_error_string example
  • Example#941 - openssl_get_cert_locations example
  • Example#942 - openssl_get_cipher_methods example
  • Example#943 - openssl_get_curve_names example
  • Example#944 - openssl_get_md_methods example
  • Example#945 - openssl_open example
  • Example#946 - openssl_pbkdf2() example
  • Example#947 - openssl_pkcs12_read example
  • Example#948 - openssl_pkcs7_decrypt example
  • Example#949 - openssl_pkcs7_encrypt example
  • Example#950 - Get a PEM array from a P7B file
  • Example#951 - openssl_pkcs7_sign example
  • Example#952 - openssl_pkey_derive example
  • Example#953 - Obtain the public key from a private key
  • Example#954 - openssl_random_pseudo_bytes example
  • Example#955 - openssl_seal example
  • Example#956 - openssl_sign example
  • Example#957 - openssl_sign example
  • Example#958 - openssl_spki_export_challenge example
  • Example#959 - openssl_spki_export_challenge example from <keygen>
  • Example#960 - openssl_spki_export example
  • Example#961 - openssl_spki_export example from <keygen>
  • Example#962 - openssl_spki_new example
  • Example#963 - openssl_spki_verify example
  • Example#964 - openssl_spki_verify example from <keygen>
  • Example#965 - openssl_verify example
  • Example#966 - openssl_verify example
  • Example#967 - openssl_x509_verify example
  • Example#968 - Basic password usage
  • Example#969 - password_hash example
  • Example#970 - password_hash example setting cost manually
  • Example#971 - password_hash example finding a good cost
  • Example#972 - password_hash example using Argon2i
  • Example#973 - Usage of password_needs_rehash
  • Example#974 - password_verify example
  • Example#975 - RNP clearsign example
  • Example#976 - simple callback function example
  • Example#977 - sodium_crypto_box_seal_open example
  • Example#978 - sodium_crypto_box_seal example
  • Example#979 - sodium_crypto_core_ristretto255_add example
  • Example#980 - sodium_crypto_core_ristretto255_from_hash example
  • Example#981 - sodium_crypto_core_ristretto255_is_valid_point example
  • Example#982 - sodium_crypto_core_ristretto255_random example
  • Example#983 - sodium_crypto_core_ristretto255_scalar_add example
  • Example#984 - sodium_crypto_core_ristretto255_scalar_invert example
  • Example#985 - sodium_crypto_core_ristretto255_scalar_negate example
  • Example#986 - sodium_crypto_core_ristretto255_scalar_random example
  • Example#987 - sodium_crypto_core_ristretto255_scalar_sub example
  • Example#988 - sodium_crypto_core_ristretto255_sub example
  • Example#989 - sodium_crypto_generichash_final example
  • Example#990 - sodium_crypto_generichash_init example
  • Example#991 - sodium_crypto_generichash_update example
  • Example#992 - sodium_crypto_kx_keypair usage
  • Example#993 - sodium_crypto_pwhash_str example
  • Example#994 - sodium_crypto_pwhash example
  • Example#995 - sodium_crypto_secretbox_keygen example
  • Example#996 - Comparing sodium_crypto_secretbox_keygen with random_bytes
  • Example#997 - sodium_crypto_secretbox_open example
  • Example#998 - sodium_crypto_secretbox example
  • Example#999 - sodium_crypto_secretstream_xchacha20poly1305_init_pull example
  • Example#1000 - sodium_crypto_secretstream_xchacha20poly1305_init_push example
  • Example#1001 - sodium_crypto_stream_xchacha20_xor_ic example
  • Example#1002 - DBA example
  • Example#1003 - Traversing a database
  • Example#1004 - dba_handlers Example
  • Example#1005 - List Privileges for a Column
  • Example#1006 - List Columns of a Table
  • Example#1007 - DSN-less connections
  • Example#1008 - odbc_connection_string_quote example
  • Example#1009 - List available DSNs
  • Example#1010 - odbc_execute and odbc_prepare example
  • Example#1011 - odbc_fetch_into examples
  • Example#1012 - odbc_next_result
  • Example#1013 - odbc_execute and odbc_prepare example
  • Example#1014 - List primary Keys of a Column
  • Example#1015 - List Columns of a stored Procedure
  • Example#1016 - List stored Procedures of a Database
  • Example#1017 - odbc_result examples
  • Example#1018 - odbc_setoption examples
  • Example#1019 - List Statistics of a Table
  • Example#1020 - List Privileges of a Table
  • Example#1021 - List Tables in a Catalog
  • Example#1022 - using PDO::ATTR_DRIVER_NAME
  • Example#1023 - Connecting to MySQL
  • Example#1024 - Handling connection errors
  • Example#1025 - Closing a connection
  • Example#1026 - Persistent connections
  • Example#1027 - Executing a batch in a transaction
  • Example#1028 - Repeated inserts using prepared statements
  • Example#1029 - Repeated inserts using prepared statements
  • Example#1030 - Fetching data using prepared statements
  • Example#1031 - Calling a stored procedure with an output parameter
  • Example#1032 - Calling a stored procedure with an input/output parameter
  • Example#1033 - Invalid use of placeholder
  • Example#1034 - Create a PDO instance and set the error mode
  • Example#1035 - Create a PDO instance and set the error mode from the constructor
  • Example#1036 - Displaying an image from a database
  • Example#1037 - Inserting an image into a database
  • Example#1038 - Inserting an image into a database: Oracle
  • Example#1039 - Roll back a transaction
  • Example#1040 - Committing a basic transaction
  • Example#1041 - Committing a DDL transaction
  • Example#1042 - Create a PDO instance via driver invocation
  • Example#1043 - Create a PDO instance via URI invocation
  • Example#1044 - Create a PDO instance using an alias
  • Example#1045 - Retrieving an SQLSTATE code
  • Example#1046 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1047 - Issuing a DELETE statement
  • Example#1048 - Retrieving database connection attributes
  • Example#1049 - A PDO::getAvailableDrivers example
  • Example#1050 - SQL statement template with named parameters
  • Example#1051 - SQL statement template with question mark parameters
  • Example#1052 - SQL statement template with question mark escaped
  • Example#1053 - SQL with no placeholders can be executed using PDO::query
  • Example#1054 - Quoting a normal string
  • Example#1055 - Quoting a dangerous string
  • Example#1056 - Quoting a complex string
  • Example#1057 - Roll back a transaction
  • Example#1058 - Binding result set output to PHP variables
  • Example#1059 - Execute a prepared statement with named placeholders
  • Example#1060 - Execute a prepared statement with question mark placeholders
  • Example#1061 - Call a stored procedure with an INOUT parameter
  • Example#1062 - Execute a prepared statement with named placeholders
  • Example#1063 - Execute a prepared statement with question mark placeholders
  • Example#1064 - A PDOStatement::closeCursor example
  • Example#1065 - Counting columns
  • Example#1066 - PDOStatement::debugDumpParams example with named parameters
  • Example#1067 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#1068 - Retrieving an SQLSTATE code
  • Example#1069 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1070 - Execute a prepared statement with a bound variable and value
  • Example#1071 - Execute a prepared statement with an array of named values
  • Example#1072 - Execute a prepared statement with an array of positional values
  • Example#1073 - Execute a prepared statement with variables bound to positional placeholders
  • Example#1074 - Execute a prepared statement using array for IN clause
  • Example#1075 - Fetching rows using different fetch styles
  • Example#1076 - Fetching rows with a scrollable cursor
  • Example#1077 - Construction order
  • Example#1078 - Fetch all remaining rows in a result set
  • Example#1079 - Fetching all values of a single column from a result set
  • Example#1080 - Grouping all values by a single column
  • Example#1081 - Instantiating a class for each result
  • Example#1082 - Calling a function for each result
  • Example#1083 - Return first column of the next row
  • Example#1084 - Retrieving column metadata
  • Example#1085 - Fetching multiple rowsets returned from a stored procedure
  • Example#1086 - Return the number of deleted rows
  • Example#1087 - Counting rows returned by a SELECT statement
  • Example#1088 - Setting the fetch mode
  • Example#1089 - Insert LOBs in CUBRID PDO
  • Example#1090 - Fetch LOBs in CUBRID PDO
  • Example#1091 - Insert set in CUBRID PDO with default data type.
  • Example#1092 - Specify data type when insert set in CUBRID PDO
  • Example#1093 - PDO_CUBRID DSN examples
  • Example#1094 - A PDO::cubrid_schema example
  • Example#1095 - PDO_DBLIB DSN examples
  • Example#1096 - PDO_FIREBIRD DSN example with path
  • Example#1097 - PDO_FIREBIRD DSN example with port and path
  • Example#1098 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1099 - PDO_FIREBIRD DSN to connect to a dialect 1 database
  • Example#1100 - PDO_IBM DSN example using db2cli.ini
  • Example#1101 - PDO_IBM DSN example using a connection string
  • Example#1102 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1103 - PDO_INFORMIX DSN example using a connection string
  • Example#1104 - Setting MySQL unbuffered mode
  • Example#1105 - PDO_MYSQL DSN examples
  • Example#1106 - PDO_SQLSRV DSN examples
  • Example#1107 - PDO_OCI DSN examples
  • Example#1108 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1109 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1110 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1111 - PDO_PGSQL DSN examples
  • Example#1112 - A PDO::pgsqlLOBCreate example
  • Example#1113 - A PDO::pgsqlLOBOpen example
  • Example#1114 - A PDO::pgsqlLOBUnlink example
  • Example#1115 - PDO_SQLITE DSN examples
  • Example#1116 - max_length aggregation function example
  • Example#1117 - PDO::sqliteCreateCollation example
  • Example#1118 - PDO::sqliteCreateFunction example
  • Example#1119 - Example of Data Retrieval
  • Example#1120 - Example of Data Insertion
  • Example#1121 - cubrid_bind example
  • Example#1122 - cubrid_bind BLOB/CLOB example
  • Example#1123 - cubrid_bind BLOB/CLOB example
  • Example#1124 - cubrid_close_prepare example
  • Example#1125 - cubrid_close_request example
  • Example#1126 - cubrid_col_get example
  • Example#1127 - cubrid_col_size example
  • Example#1128 - cubrid_column_names example
  • Example#1129 - cubrid_column_types example
  • Example#1130 - cubrid_commit example
  • Example#1131 - cubrid_connect_with_url url without properties example
  • Example#1132 - cubrid_connect_with_url url with properties example
  • Example#1133 - cubrid_connect example
  • Example#1134 - cubrid_current_oid example
  • Example#1135 - cubrid_disconnect example
  • Example#1136 - cubrid_drop example
  • Example#1137 - cubrid_error_code_facility example
  • Example#1138 - cubrid_error_code example
  • Example#1139 - cubrid_error_msg example
  • Example#1140 - cubrid_execute example
  • Example#1141 - cubrid_fetch example
  • Example#1142 - cubrid_free_result example
  • Example#1143 - cubrid_get_charset example
  • Example#1144 - cubrid_get_class_name example
  • Example#1145 - cubrid_get_client_info example
  • Example#1146 - cubrid_get_db_parameter example
  • Example#1147 - cubrid_get_query_timeout example
  • Example#1148 - cubrid_get_server_info example
  • Example#1149 - cubrid_get example
  • Example#1150 - cubrid_insert_id example
  • Example#1151 - cubrid_is_instance example
  • Example#1152 - cubrid_lob_close example
  • Example#1153 - cubrid_lob_export example
  • Example#1154 - cubrid_lob_get example
  • Example#1155 - cubrid_lob_send example
  • Example#1156 - cubrid_lob_size example
  • Example#1157 - cubrid_lob2_bind example
  • Example#1158 - cubrid_lob2_export example
  • Example#1159 - cubrid_lob2_export example
  • Example#1160 - cubrid_lob2_read example 1
  • Example#1161 - cubrid_lob2_read example 2
  • Example#1162 - cubrid_lob2_seek64 example
  • Example#1163 - cubrid_lob2_seek example
  • Example#1164 - cubrid_lob2_write example 1
  • Example#1165 - cubrid_lob2_write example 2
  • Example#1166 - cubrid_lock_read example
  • Example#1167 - cubrid_lock_write example
  • Example#1168 - cubrid_move_cursor example
  • Example#1169 - cubrid_next_result example
  • Example#1170 - cubrid_num_cols example
  • Example#1171 - cubrid_num_rows example
  • Example#1172 - cubrid_pconnect_with_url url without properties example
  • Example#1173 - cubrid_pconnect_with_url url with properties example
  • Example#1174 - cubrid_connect example
  • Example#1175 - cubrid_prepare example
  • Example#1176 - cubrid_put example
  • Example#1177 - cubrid_rollback example
  • Example#1178 - cubrid_schema example
  • Example#1179 - cubrid_seq_drop example
  • Example#1180 - cubrid_seq_insert example
  • Example#1181 - cubrid_seq_put example
  • Example#1182 - cubrid_set_add example
  • Example#1183 - cubrid_get_db_parameter example
  • Example#1184 - cubrid_set_drop example
  • Example#1185 - cubrid_version example
  • Example#1186 - cubrid_affected_rows example
  • Example#1187 - cubrid_client_encoding example
  • Example#1188 - cubrid_close example
  • Example#1189 - cubrid_data_seek example
  • Example#1190 - cubrid_db_name example
  • Example#1191 - cubrid_errno example
  • Example#1192 - cubrid_error example
  • Example#1193 - cubrid_fetch_array example
  • Example#1194 - cubrid_fetch_assoc example
  • Example#1195 - cubrid_fetch_field example
  • Example#1196 - cubrid_fetch_lengths example
  • Example#1197 - cubrid_fetch_object example
  • Example#1198 - cubrid_fetch_row example
  • Example#1199 - cubrid_field_flags example
  • Example#1200 - cubrid_field_len example
  • Example#1201 - cubrid_field_name example
  • Example#1202 - cubrid_field_seek example
  • Example#1203 - cubrid_field_table example
  • Example#1204 - cubrid_field_type example
  • Example#1205 - cubrid_list_dbs example
  • Example#1206 - cubrid_num_fields example
  • Example#1207 - cubrid_ping example
  • Example#1208 - Invalid Query
  • Example#1209 - Valid Query
  • Example#1210 - cubrid_real_escape_string example
  • Example#1211 - cubrid_result example
  • Example#1212 - cubrid_unbuffered_query example
  • Example#1213 - cubrid_load_from_glo example
  • Example#1214 - cubrid_new_glo example
  • Example#1215 - cubrid_save_to_glo example
  • Example#1216 - cubrid_send_glo example
  • Example#1217 - Inserting a record in a dBase database
  • Example#1218 - Closing a dBase database file
  • Example#1219 - Creating a dBase database file
  • Example#1220 - Showing header information for a dBase database file
  • Example#1221 - Listing all the registered members in the database
  • Example#1222 - dbase_numfields Example
  • Example#1223 - Looping over all the records of the database
  • Example#1224 - Opening a dBase database file
  • Example#1225 - Emptying a dBase database
  • Example#1226 - Updating a record in the database
  • Example#1227 - ibase_backup example
  • Example#1228 - ibase_backup example with arguments
  • Example#1229 - ibase_blob_get example
  • Example#1230 - ibase_blob_import example
  • Example#1231 - ibase_connect example
  • Example#1232 - ibase_execute example
  • Example#1233 - ibase_fetch_object example
  • Example#1234 - ibase_field_info example
  • Example#1235 - ibase_name_result example
  • Example#1236 - ibase_num_fields example
  • Example#1237 - ibase_query example
  • Example#1238 - ibase_restore example
  • Example#1239 - ibase_restore example with arguments
  • Example#1240 - ibase_service_attach example
  • Example#1241 - ibase_service_attach example
  • Example#1242 - ibase_service_attach example using hostname/port syntax
  • Example#1243 - ibase_service_detach example
  • Example#1244 - ibase_set_event_handler example
  • Example#1245 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1246 - Setting the AUTOCOMMIT value for a connection
  • Example#1247 - Binding PHP variables to a prepared statement
  • Example#1248 - Calling stored procedures with IN and OUT parameters
  • Example#1249 - Inserting a binary large object (BLOB) directly from a file
  • Example#1250 - A db2_client_info example
  • Example#1251 - Closing a connection
  • Example#1252 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1253 - Retrieving the error message returned by a failed connection attempt
  • Example#1254 - Creating a cataloged connection
  • Example#1255 - Creating an uncataloged connection
  • Example#1256 - Creating a connection with autocommit off by default
  • Example#1257 - i5/OS best performance
  • Example#1258 - Using trusted context
  • Example#1259 - A db2_escape_string example
  • Example#1260 - Creating a table with db2_exec
  • Example#1261 - Executing a SELECT statement with a scrollable cursor
  • Example#1262 - Returning XML data as an SQL ResultSet
  • Example#1263 - Performing a "JOIN" with XML data
  • Example#1264 - Returning SQL data as part of a larger XML document
  • Example#1265 - Preparing and executing an SQL statement with parameter markers
  • Example#1266 - Calling a stored procedure with an OUT parameter
  • Example#1267 - Returning XML data as an SQL ResultSet
  • Example#1268 - Performing a "JOIN" with XML data
  • Example#1269 - Returning SQL data as part of a larger XML document
  • Example#1270 - Iterating through a forward-only cursor
  • Example#1271 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1272 - Iterating through a forward-only cursor
  • Example#1273 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1274 - Iterating through a forward-only cursor
  • Example#1275 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1276 - A db2_fetch_object example
  • Example#1277 - Iterating through a result set
  • Example#1278 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1279 - Setting and retrieving parameters through a connection resource
  • Example#1280 - A db2_last_insert_id example
  • Example#1281 - Iterating through different types of data
  • Example#1282 - Calling a stored procedure that returns multiple result sets
  • Example#1283 - Retrieving the number of fields in a result set
  • Example#1284 - Closing a persistent connection
  • Example#1285 - A db2_pconnect example
  • Example#1286 - Using trusted context
  • Example#1287 - Preparing and executing an SQL statement with parameter markers
  • Example#1288 - A db2_result example
  • Example#1289 - Rolling back a DELETE statement
  • Example#1290 - A db2_server_info example
  • Example#1291 - Setting one parameter with a connection resource
  • Example#1292 - Setting multiple parameters with a connection resource
  • Example#1293 - Setting multiple parameters with an invalid key
  • Example#1294 - Setting multiple parameters with an invalid value
  • Example#1295 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1296 - Setting multiple parameters with the wrong resource
  • Example#1297 - Putting it all together
  • Example#1298 - i5/OS cursors are read-only
  • Example#1299 - MongoDB\Driver\Manager::__construct basic example
  • Example#1300 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1301 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1302 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1303 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1304 - Limiting execution time for a command
  • Example#1305 - MongoDB\Driver\Manager::executeQuery example
  • Example#1306 - Limiting execution time for a query
  • Example#1307 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1308 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1309 - MongoDB\Driver\Manager::getServers example
  • Example#1310 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1311 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1312 - MongoDB\Driver\Command::__construct example
  • Example#1313 - MongoDB\Driver\Command::__construct example
  • Example#1314 - MongoDB\Driver\Query::__construct example
  • Example#1315 - Mixed write operations are grouped by type
  • Example#1316 - Ordered write operations causing an error
  • Example#1317 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1318 - MongoDB\Driver\BulkWrite::count example
  • Example#1319 - MongoDB\Driver\BulkWrite::delete example
  • Example#1320 - MongoDB\Driver\BulkWrite::insert example
  • Example#1321 - MongoDB\Driver\BulkWrite::update example
  • Example#1322 - Declare an API version on a manager
  • Example#1323 - Declare a strict API version on a manager
  • Example#1324 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1325 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1326 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1327 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1328 - MongoDB\Driver\WriteConcern::getW example
  • Example#1329 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1330 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1331 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1332 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1333 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1334 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1335 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1336 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1337 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1338 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1339 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1340 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1341 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1342 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1343 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1344 - Reading a result set
  • Example#1345 - Reading a result set for a tailable cursor
  • Example#1346 - MongoDB\Driver\Cursor::getId example
  • Example#1347 - MongoDB\Driver\Cursor::getServer example
  • Example#1348 - MongoDB\Driver\Cursor::isDead example
  • Example#1349 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1350 - MongoDB\Driver\Cursor::toArray example
  • Example#1351 - MongoDB\Driver\CursorId::__toString example
  • Example#1352 - MongoDB\Driver\Server::getHost example
  • Example#1353 - MongoDB\Driver\Server::getInfo example
  • Example#1354 - MongoDB\Driver\Server::getLatency example
  • Example#1355 - MongoDB\Driver\Server::getPort example
  • Example#1356 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1357 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1358 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1359 - MongoDB\Driver\WriteError::getCode example
  • Example#1360 - MongoDB\Driver\WriteError::getIndex example
  • Example#1361 - MongoDB\Driver\WriteError::getMessage example
  • Example#1362 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1363 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1364 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1365 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1366 - MongoDB\Driver\WriteResult::getServer example
  • Example#1367 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1368 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1369 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1370 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1371 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1372 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1373 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1374 - MongoDB\BSON\fromJSON example
  • Example#1375 - MongoDB\BSON\fromPHP example
  • Example#1376 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1377 - MongoDB\BSON\toJSON example
  • Example#1378 - MongoDB\BSON\toPHP example
  • Example#1379 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1380 - MongoDB\BSON\Document::toCanonicalExtendedJSON example
  • Example#1381 - MongoDB\BSON\Document::toRelaxedExtendedJSON example
  • Example#1382 - MongoDB\BSON\Binary::__construct example
  • Example#1383 - MongoDB\BSON\Binary::getData example
  • Example#1384 - MongoDB\BSON\Binary::getType example
  • Example#1385 - MongoDB\BSON\Binary::__toString example
  • Example#1386 - MongoDB\BSON\Decimal128::__construct example
  • Example#1387 - MongoDB\BSON\Decimal128::__toString example
  • Example#1388 - MongoDB\BSON\Javascript::__construct example
  • Example#1389 - MongoDB\BSON\Javascript::getCode example
  • Example#1390 - MongoDB\BSON\Javascript::getScope example
  • Example#1391 - MongoDB\BSON\Javascript::__toString example
  • Example#1392 - MongoDB\BSON\MaxKey::__construct example
  • Example#1393 - MongoDB\BSON\MinKey::__construct example
  • Example#1394 - MongoDB\BSON\ObjectId::__construct example
  • Example#1395 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1396 - MongoDB\BSON\ObjectId::__toString example
  • Example#1397 - MongoDB\BSON\Regex::__construct example
  • Example#1398 - MongoDB\BSON\Regex::getFlags example
  • Example#1399 - MongoDB\BSON\Regex::getPattern example
  • Example#1400 - MongoDB\BSON\Regex::__toString example
  • Example#1401 - MongoDB\BSON\Timestamp::__construct example
  • Example#1402 - MongoDB\BSON\Timestamp::__toString example
  • Example#1403 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1404 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1405 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1406 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1407 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1408 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1409 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1410 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1411 - MongoDB\BSON\Int64::__toString example
  • Example#1412 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1413 - Comparing the MySQL APIs
  • Example#1414 - Comparing prepared statements
  • Example#1415 - Configure commands for using mysqlnd or libmysqlclient
  • Example#1416 - Unbuffered query example: mysqli
  • Example#1417 - Unbuffered query example: pdo_mysql
  • Example#1418 - Problems with setting the character set with SQL
  • Example#1419 - Setting the character set example: mysqli
  • Example#1420 - Setting the character set example: pdo_mysql
  • Example#1421 - Easy migration from the old mysql extension
  • Example#1422 - Object-oriented and procedural interface
  • Example#1423 - Bad coding style
  • Example#1424 - Special meaning of localhost
  • Example#1425 - Setting defaults
  • Example#1426 - Executing queries
  • Example#1427 - Navigation through buffered results
  • Example#1428 - Navigation through unbuffered results
  • Example#1429 - Text protocol returns strings by default
  • Example#1430 - Native data types with mysqlnd and connection option
  • Example#1431 - Prepared statement
  • Example#1432 - INSERT prepared once, executed multiple times
  • Example#1433 - Less round trips using multi-INSERT SQL
  • Example#1434 - Native datatypes
  • Example#1435 - Output variable binding
  • Example#1436 - Using mysqli_result to fetch results
  • Example#1437 - Buffered result set for flexible read out
  • Example#1438 - Calling a stored procedure
  • Example#1439 - Using session variables
  • Example#1440 - Fetching results from stored procedures
  • Example#1441 - Stored Procedures and Prepared Statements
  • Example#1442 - Stored Procedures and Prepared Statements using bind API
  • Example#1443 - Multiple Statements
  • Example#1444 - SQL Injection
  • Example#1445 - Setting autocommit mode with SQL and through the API
  • Example#1446 - Commit and rollback
  • Example#1447 - Accessing result set meta data
  • Example#1448 - Prepared statements metadata
  • Example#1449 - $mysqli->affected_rows example
  • Example#1450 - mysqli::autocommit example
  • Example#1451 - mysqli::begin_transaction example
  • Example#1452 - mysqli::change_user example
  • Example#1453 - mysqli::character_set_name example
  • Example#1454 - mysqli::close example
  • Example#1455 - $mysqli->connect_errno example
  • Example#1456 - $mysqli->connect_error example
  • Example#1457 - mysqli::__construct example
  • Example#1458 - Extending mysqli class
  • Example#1459 - Manual error handling
  • Example#1460 - Generating a Trace File
  • Example#1461 - $mysqli->errno example
  • Example#1462 - $mysqli->error_list example
  • Example#1463 - $mysqli->error example
  • Example#1464 - mysqli::execute_query example
  • Example#1465 - $mysqli->field_count example
  • Example#1466 - mysqli::get_charset example
  • Example#1467 - mysqli_get_client_info
  • Example#1468 - mysqli_get_client_version
  • Example#1469 - A mysqli_get_connection_stats example
  • Example#1470 - $mysqli->host_info example
  • Example#1471 - $mysqli->protocol_version example
  • Example#1472 - $mysqli->server_info example
  • Example#1473 - $mysqli->server_version example
  • Example#1474 - $mysqli->info example
  • Example#1475 - $mysqli->insert_id example
  • Example#1476 - mysqli::kill example
  • Example#1477 - mysqli::multi_query example
  • Example#1478 - mysqli::ping example
  • Example#1479 - A mysqli_poll example
  • Example#1480 - mysqli::prepare example
  • Example#1481 - mysqli::query example
  • Example#1482 - mysqli::real_connect example
  • Example#1483 - mysqli::real_escape_string example
  • Example#1484 - mysqli::select_db example
  • Example#1485 - mysqli::set_charset example
  • Example#1486 - $mysqli->sqlstate example
  • Example#1487 - mysqli::stat example
  • Example#1488 - $mysqli->thread_id example
  • Example#1489 - mysqli::use_result example
  • Example#1490 - $mysqli->warning_count example
  • Example#1491 - mysqli_stmt_affected_rows example
  • Example#1492 - mysqli_stmt::bind_param example
  • Example#1493 - Using ... to provide arguments
  • Example#1494 - Object-oriented style
  • Example#1495 - Procedural style
  • Example#1496 - Object-oriented style
  • Example#1497 - Procedural style
  • Example#1498 - Object-oriented style
  • Example#1499 - Procedural style
  • Example#1500 - Object-oriented style
  • Example#1501 - Procedural style
  • Example#1502 - Object-oriented style
  • Example#1503 - Procedural style
  • Example#1504 - Execute a prepared statement with bound variables
  • Example#1505 - Execute a prepared statement with an array of values
  • Example#1506 - Object-oriented style
  • Example#1507 - Procedural style
  • Example#1508 - Object-oriented style
  • Example#1509 - Procedural style
  • Example#1510 - Object-oriented style
  • Example#1511 - Procedural style
  • Example#1512 - Object-oriented style
  • Example#1513 - Procedural style
  • Example#1514 - Object-oriented style
  • Example#1515 - Procedural style
  • Example#1516 - mysqli_stmt::prepare example
  • Example#1517 - Object-oriented style
  • Example#1518 - Procedural style
  • Example#1519 - Object-oriented style
  • Example#1520 - Object-oriented style
  • Example#1521 - Procedural style
  • Example#1522 - Object-oriented style
  • Example#1523 - Procedural style
  • Example#1524 - Creation of a mysqli_result object
  • Example#1525 - Object-oriented style
  • Example#1526 - Procedural style
  • Example#1527 - mysqli::data_seek example
  • Example#1528 - Adjusting the result pointer when iterating
  • Example#1529 - mysqli_result::fetch_all example
  • Example#1530 - mysqli_result::fetch_array example
  • Example#1531 - mysqli_result::fetch_assoc example
  • Example#1532 - Comparison of mysqli_result iterator and mysqli_result::fetch_assoc usage
  • Example#1533 - mysqli_result::fetch_column example
  • Example#1534 - Object-oriented style
  • Example#1535 - Procedural style
  • Example#1536 - Object-oriented style
  • Example#1537 - Procedural style
  • Example#1538 - Object-oriented style
  • Example#1539 - Procedural style
  • Example#1540 - mysqli_result::fetch_object example
  • Example#1541 - mysqli_result::fetch_row example
  • Example#1542 - Object-oriented style
  • Example#1543 - Procedural style
  • Example#1544 - Object-oriented style
  • Example#1545 - Procedural style
  • Example#1546 - Object-oriented style
  • Example#1547 - Procedural style
  • Example#1548 - Object-oriented style
  • Example#1549 - Procedural style
  • Example#1550 - Object-oriented style
  • Example#1551 - Procedural style
  • Example#1552 - Error reporting except bad index errors
  • Example#1553 - A mysqli_get_client_stats example
  • Example#1554 - Connecting to a MySQL Server
  • Example#1555 - Creating a Schema and Collection on the MySQL Server
  • Example#1556 - Storing and Retrieving Data
  • Example#1557 - Fetching and Iterating Multiple Documents
  • Example#1558 - mysql_xdevapi\Expression example
  • Example#1559 - URI examples
  • Example#1560 - mysql_xdevapi\getSession example
  • Example#1561 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1562 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1563 - mysql_xdevapi\Client::__construct example
  • Example#1564 - mysql_xdevapi\Collection::add example
  • Example#1565 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#1566 - mysql_xdevapi\Collection::getOne example
  • Example#1567 - mysql_xdevapi\Collection::count example
  • Example#1568 - mysql_xdevapi\Collection::createIndex example
  • Example#1569 - mysql_xdevapi\Collection::dropIndex example
  • Example#1570 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#1571 - mysql_xdevapi\Collection::find example
  • Example#1572 - mysql_xdevapi\Collection::getName example
  • Example#1573 - mysql_xdevapi\Collection::getOne example
  • Example#1574 - mysql_xdevapi\Collection::getSchema example
  • Example#1575 - mysql_xdevapi\Collection::getSession example
  • Example#1576 - mysql_xdevapi\Collection::modify example
  • Example#1577 - mysql_xdevapi\Collection::remove example
  • Example#1578 - mysql_xdevapi\Collection::removeOne example
  • Example#1579 - mysql_xdevapi\Collection::replaceOne example
  • Example#1580 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#1581 - mysql_xdevapi\CollectionAdd::execute example
  • Example#1582 - mysql_xdevapi\CollectionFind::bind example
  • Example#1583 - CollectionFind example
  • Example#1584 - CollectionFind example
  • Example#1585 - mysql_xdevapi\CollectionFind::fields example
  • Example#1586 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#1587 - mysql_xdevapi\CollectionFind::having example
  • Example#1588 - mysql_xdevapi\CollectionFind::limit example
  • Example#1589 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#1590 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#1591 - mysql_xdevapi\CollectionFind::offset example
  • Example#1592 - mysql_xdevapi\CollectionFind::sort example
  • Example#1593 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#1594 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#1595 - mysql_xdevapi\CollectionModify::bind example
  • Example#1596 - mysql_xdevapi\CollectionModify::__construct example
  • Example#1597 - mysql_xdevapi\CollectionModify::execute example
  • Example#1598 - mysql_xdevapi\CollectionModify::limit example
  • Example#1599 - mysql_xdevapi\CollectionModify::patch example
  • Example#1600 - mysql_xdevapi\CollectionModify::replace example
  • Example#1601 - mysql_xdevapi\CollectionModify::set example
  • Example#1602 - mysql_xdevapi\CollectionModify::skip example
  • Example#1603 - mysql_xdevapi\CollectionModify::sort example
  • Example#1604 - mysql_xdevapi\CollectionModify::unset example
  • Example#1605 - mysql_xdevapi\CollectionRemove::bind example
  • Example#1606 - mysql_xdevapi\Collection::remove example
  • Example#1607 - mysql_xdevapi\CollectionRemove::execute example
  • Example#1608 - mysql_xdevapi\CollectionRemove::limit example
  • Example#1609 - mysql_xdevapi\CollectionRemove::sort example
  • Example#1610 - mysql_xdevapi\ColumnResult::__construct example
  • Example#1611 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#1612 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#1613 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#1614 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#1615 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#1616 - mysql_xdevapi\ColumnResult::getLength example
  • Example#1617 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#1618 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#1619 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#1620 - mysql_xdevapi\ColumnResult::getType example
  • Example#1621 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#1622 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#1623 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#1624 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#1625 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#1626 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#1627 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#1628 - mysql_xdevapi\DatabaseObject::getName example
  • Example#1629 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#1630 - A DocResult example
  • Example#1631 - mysql_xdevapi\DocResult::fetchAll example
  • Example#1632 - mysql_xdevapi\DocResult::fetchOne example
  • Example#1633 - mysql_xdevapi\DocResult::getWarnings example
  • Example#1634 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#1635 - execute() examples
  • Example#1636 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#1637 - mysql_xdevapi\Expression::__construct example
  • Example#1638 - mysql_xdevapi\Result::__construct example
  • Example#1639 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#1640 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#1641 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#1642 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1643 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1644 - mysql_xdevapi\RowResult::__construct example
  • Example#1645 - mysql_xdevapi\RowResult::fetchAll example
  • Example#1646 - mysql_xdevapi\RowResult::fetchOne example
  • Example#1647 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#1648 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#1649 - mysql_xdevapi\RowResult::getColumns example
  • Example#1650 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1651 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1652 - Schema::__construct example
  • Example#1653 - Schema::createCollection example
  • Example#1654 - Schema::createCollection validate parameter example
  • Example#1655 - Schema::dropCollection example
  • Example#1656 - Schema::existsInDatabase example
  • Example#1657 - Schema::getCollection example
  • Example#1658 - Schema::getCollectionAsTable example
  • Example#1659 - mysql_xdevapi\Schema::getCollections example
  • Example#1660 - mysql_xdevapi\Schema::getName example
  • Example#1661 - mysql_xdevapi\Schema::getSession example
  • Example#1662 - mysql_xdevapi\Schema::getTable example
  • Example#1663 - mysql_xdevapi\Schema::getTables example
  • Example#1664 - mysql_xdevapi\Session::getSchema example
  • Example#1665 - mysql_xdevapi\Session::close example
  • Example#1666 - mysql_xdevapi\Session::commit example
  • Example#1667 - mysql_xdevapi\Session::__construct example
  • Example#1668 - mysql_xdevapi\Session::createSchema example
  • Example#1669 - mysql_xdevapi\Session::dropSchema example
  • Example#1670 - mysql_xdevapi\Session::generateUuid example
  • Example#1671 - mysql_xdevapi\Session::getSchema example
  • Example#1672 - mysql_xdevapi\Session::getSchema example
  • Example#1673 - mysql_xdevapi\Session::getSchemas example
  • Example#1674 - mysql_xdevapi\Session::getServerVersion example
  • Example#1675 - mysql_xdevapi\Session::listClients example
  • Example#1676 - mysql_xdevapi\Session::quoteName example
  • Example#1677 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#1678 - mysql_xdevapi\Session::rollback example
  • Example#1679 - mysql_xdevapi\Session::rollbackTo example
  • Example#1680 - mysql_xdevapi\Session::setSavepoint example
  • Example#1681 - mysql_xdevapi\Session::sql example
  • Example#1682 - mysql_xdevapi\Session::startTransaction example
  • Example#1683 - mysql_xdevapi\SqlStatement::bind example
  • Example#1684 - mysql_xdevapi\SqlStatement::__construct example
  • Example#1685 - mysql_xdevapi\SqlStatement::execute example
  • Example#1686 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#1687 - mysql_xdevapi\SqlStatement::getResult example
  • Example#1688 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#1689 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#1690 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#1691 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#1692 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#1693 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#1694 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#1695 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#1696 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#1697 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#1698 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#1699 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#1700 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#1701 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#1702 - mysql_xdevapi\Statement::__construct example
  • Example#1703 - mysql_xdevapi\Statement::getNextResult example
  • Example#1704 - mysql_xdevapi\Statement::getResult example
  • Example#1705 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#1706 - mysql_xdevapi\Table::__construct example
  • Example#1707 - mysql_xdevapi\Table::count example
  • Example#1708 - mysql_xdevapi\Table::delete example
  • Example#1709 - mysql_xdevapi\Table::existsInDatabase example
  • Example#1710 - mysql_xdevapi\Table::getName example
  • Example#1711 - mysql_xdevapi\Table::getSchema example
  • Example#1712 - mysql_xdevapi\Table::getSession example
  • Example#1713 - mysql_xdevapi\Table::insert example
  • Example#1714 - mysql_xdevapi\Table::isView example
  • Example#1715 - mysql_xdevapi\Table::count example
  • Example#1716 - mysql_xdevapi\Table::update example
  • Example#1717 - mysql_xdevapi\TableDelete::bind example
  • Example#1718 - mysql_xdevapi\TableDelete::__construct example
  • Example#1719 - mysql_xdevapi\TableDelete::execute example
  • Example#1720 - mysql_xdevapi\TableDelete::limit example
  • Example#1721 - mysql_xdevapi\TableDelete::orderBy example
  • Example#1722 - mysql_xdevapi\TableDelete::where example
  • Example#1723 - mysql_xdevapi\TableInsert::__construct example
  • Example#1724 - mysql_xdevapi\TableInsert::execute example
  • Example#1725 - mysql_xdevapi\TableInsert::values example
  • Example#1726 - mysql_xdevapi\TableSelect::bind example
  • Example#1727 - mysql_xdevapi\TableSelect::__construct example
  • Example#1728 - mysql_xdevapi\TableSelect::execute example
  • Example#1729 - mysql_xdevapi\TableSelect::groupBy example
  • Example#1730 - mysql_xdevapi\TableSelect::having example
  • Example#1731 - mysql_xdevapi\TableSelect::limit example
  • Example#1732 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#1733 - mysql_xdevapi\TableSelect::lockShared example
  • Example#1734 - mysql_xdevapi\TableSelect::offset example
  • Example#1735 - mysql_xdevapi\TableSelect::orderBy example
  • Example#1736 - mysql_xdevapi\TableSelect::where example
  • Example#1737 - mysql_xdevapi\TableUpdate::bind example
  • Example#1738 - mysql_xdevapi\TableUpdate::__construct example
  • Example#1739 - mysql_xdevapi\TableUpdate::execute example
  • Example#1740 - mysql_xdevapi\TableUpdate::limit example
  • Example#1741 - mysql_xdevapi\TableUpdate::orderby example
  • Example#1742 - mysql_xdevapi\TableUpdate::set example
  • Example#1743 - mysql_xdevapi\TableUpdate::where example
  • Example#1744 - mysql_xdevapi\Warning::__construct example
  • Example#1745 - MySQL extension overview example
  • Example#1746 - mysql_affected_rows example
  • Example#1747 - mysql_affected_rows example using transactions
  • Example#1748 - mysql_client_encoding example
  • Example#1749 - mysql_close example
  • Example#1750 - mysql_connect example
  • Example#1751 - mysql_connect example using hostname:port syntax
  • Example#1752 - mysql_connect example using ":/path/to/socket" syntax
  • Example#1753 - mysql_create_db alternative example
  • Example#1754 - mysql_data_seek example
  • Example#1755 - mysql_db_name example
  • Example#1756 - mysql_db_query alternative example
  • Example#1757 - mysql_drop_db alternative example
  • Example#1758 - mysql_errno example
  • Example#1759 - mysql_error example
  • Example#1760 - mysql_escape_string example
  • Example#1761 - Query with aliased duplicate field names
  • Example#1762 - mysql_fetch_array with MYSQL_NUM
  • Example#1763 - mysql_fetch_array with MYSQL_ASSOC
  • Example#1764 - mysql_fetch_array with MYSQL_BOTH
  • Example#1765 - An expanded mysql_fetch_assoc example
  • Example#1766 - mysql_fetch_field example
  • Example#1767 - A mysql_fetch_lengths example
  • Example#1768 - mysql_fetch_object example
  • Example#1769 - mysql_fetch_object example
  • Example#1770 - Fetching one row with mysql_fetch_row
  • Example#1771 - A mysql_field_flags example
  • Example#1772 - mysql_field_len example
  • Example#1773 - mysql_field_name example
  • Example#1774 - A mysql_field_table example
  • Example#1775 - mysql_field_type example
  • Example#1776 - A mysql_free_result example
  • Example#1777 - mysql_get_client_info example
  • Example#1778 - mysql_get_host_info example
  • Example#1779 - mysql_get_proto_info example
  • Example#1780 - mysql_get_server_info example
  • Example#1781 - Relevant MySQL Statements
  • Example#1782 - mysql_insert_id example
  • Example#1783 - mysql_list_dbs example
  • Example#1784 - Alternate to deprecated mysql_list_fields
  • Example#1785 - mysql_list_processes example
  • Example#1786 - mysql_list_tables alternative example
  • Example#1787 - A mysql_num_fields example
  • Example#1788 - mysql_num_rows example
  • Example#1789 - A mysql_ping example
  • Example#1790 - Invalid Query
  • Example#1791 - Valid Query
  • Example#1792 - Simple mysql_real_escape_string example
  • Example#1793 - mysql_real_escape_string requires a connection example
  • Example#1794 - An example SQL Injection Attack
  • Example#1795 - mysql_result example
  • Example#1796 - mysql_select_db example
  • Example#1797 - mysql_stat example
  • Example#1798 - Alternative mysql_stat example
  • Example#1799 - mysql_tablename example
  • Example#1800 - mysql_thread_id example
  • Example#1801 - Basic query
  • Example#1802 - Inserting with bind variables
  • Example#1803 - Binding in the WHERE clause of a query
  • Example#1804 - Inserting and fetching a CLOB
  • Example#1805 - Using a PL/SQL stored function
  • Example#1806 - Using a PL/SQL stored procedure
  • Example#1807 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#1808 -
  • Example#1809 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#1810 - oci_bind_array_by_name example
  • Example#1811 - Inserting data with oci_bind_by_name
  • Example#1812 - Binding once for multiple executions
  • Example#1813 - Binding with a foreach loop
  • Example#1814 - Binding in a WHERE clause
  • Example#1815 - Binding with a LIKE clause
  • Example#1816 - Binding with REGEXP_LIKE
  • Example#1817 - Binding Multiple Values in an IN Clause
  • Example#1818 - Binding a ROWID returned by a query
  • Example#1819 - Binding a ROWID on INSERT
  • Example#1820 - Binding for a PL/SQL stored function
  • Example#1821 - Binding parameters for a PL/SQL stored procedure
  • Example#1822 - Binding a CLOB column
  • Example#1823 - Binding a PL/SQL BOOLEAN
  • Example#1824 - oci_client_version example
  • Example#1825 - Closing a connection
  • Example#1826 - Database connections are not closed until all references are closed
  • Example#1827 - Closing a connection opened more than once
  • Example#1828 - Connections are closed when variables go out of scope
  • Example#1829 - oci_commit example
  • Example#1830 - Basic oci_connect using Easy Connect syntax
  • Example#1831 - Basic oci_connect using a Network Connect name
  • Example#1832 - oci_connect with an explicit character set
  • Example#1833 - Using multiple calls to oci_connect
  • Example#1834 - oci_define_by_name example
  • Example#1835 - oci_define_by_name with case sensitive column names
  • Example#1836 - oci_define_by_name with LOB columns
  • Example#1837 - oci_define_by_name with an explicit type
  • Example#1838 - Displaying the Oracle error message after a connection error
  • Example#1839 - Displaying the Oracle error message after a parsing error
  • Example#1840 - Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
  • Example#1841 - oci_execute for queries
  • Example#1842 - oci_execute without specifying a mode example
  • Example#1843 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#1844 - oci_execute with different commit modes example
  • Example#1845 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#1846 - oci_fetch_all example
  • Example#1847 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#1848 - oci_fetch_all with OCI_NUM
  • Example#1849 - oci_fetch_array with OCI_BOTH
  • Example#1850 - oci_fetch_array with OCI_NUM
  • Example#1851 - oci_fetch_array with OCI_ASSOC
  • Example#1852 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#1853 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#1854 - oci_fetch_array with case sensitive column names
  • Example#1855 - oci_fetch_array with columns having duplicate names
  • Example#1856 - oci_fetch_array with DATE columns
  • Example#1857 - oci_fetch_array with REF CURSOR
  • Example#1858 - Pagination with oci_fetch_array using a LIMIT-like query
  • Example#1859 - oci_fetch_array with Oracle Database Implicit Result Sets
  • Example#1860 - oci_fetch_assoc Example
  • Example#1861 - oci_fetch_object example
  • Example#1862 - oci_fetch_object with case sensitive column names
  • Example#1863 - oci_fetch_object with LOBs
  • Example#1864 - oci_fetch_row Example
  • Example#1865 - oci_fetch with defined variables
  • Example#1866 - oci_fetch with oci_result
  • Example#1867 - oci_field_name example
  • Example#1868 - oci_field_name example
  • Example#1869 - oci_field_precision Example
  • Example#1870 - oci_field_scale Example
  • Example#1871 - oci_field_size example
  • Example#1872 - oci_field_type_raw Example
  • Example#1873 - oci_field_type example
  • Example#1874 - Fetching Implicit Result Sets in a loop
  • Example#1875 - Getting child statement handles individually
  • Example#1876 - Explicitly setting the Prefetch Count
  • Example#1877 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#1878 - oci_new_connect example
  • Example#1879 - Binding a REF CURSOR in an Oracle stored procedure call
  • Example#1880 - oci_new_descriptor example
  • Example#1881 - oci_new_descriptor example
  • Example#1882 - oci_num_fields example
  • Example#1883 - oci_num_rows example
  • Example#1884 - oci_parse example for SQL statements
  • Example#1885 - oci_parse example for PL/SQL statements
  • Example#1886 - oci_password_change example changing the password of an already connected user
  • Example#1887 - oci_password_change example of connecting and changing the password in one step
  • Example#1888 - Basic oci_pconnect Example using Easy Connect syntax
  • Example#1889 - oci_fetch with oci_result
  • Example#1890 - oci_rollback example
  • Example#1891 - Rolling back to a SAVEPOINT example
  • Example#1892 - oci_server_version example
  • Example#1893 - Setting the action
  • Example#1894 - Setting the timeout
  • Example#1895 - Setting the client identifier to the application user
  • Example#1896 - Setting the client information
  • Example#1897 - Setting the DBOP
  • Example#1898 - Two scripts can use different versions of myfunc() at the same time
  • Example#1899 - Setting the module name
  • Example#1900 - Changing the LOB prefetch value for a query
  • Example#1901 - Changing the default prefetch value for a query
  • Example#1902 - Changing the default prefetch for a REF CURSOR fetch
  • Example#1903 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#1904 - oci_statement_type example
  • Example#1905 - PostgreSQL extension overview example
  • Example#1906 - PostgreSQL user defined functions example
  • Example#1907 - pg_affected_rows example
  • Example#1908 - pg_cancel_query example
  • Example#1909 - pg_client_encoding example
  • Example#1910 - pg_close example
  • Example#1911 - Using pg_connect
  • Example#1912 - pg_connection_busy example
  • Example#1913 - pg_connection_reset example
  • Example#1914 - pg_connection_status example
  • Example#1915 - pg_convert example
  • Example#1916 - pg_copy_from example
  • Example#1917 - pg_copy_to example
  • Example#1918 - pg_dbname example
  • Example#1919 - pg_delete example
  • Example#1920 - pg_end_copy example
  • Example#1921 - pg_escape_bytea example
  • Example#1922 - pg_escape_identifier example
  • Example#1923 - pg_escape_literal example
  • Example#1924 - pg_escape_string example
  • Example#1925 - Using pg_execute
  • Example#1926 - pg_fetch_all_columns example
  • Example#1927 - PostgreSQL fetch all
  • Example#1928 - pg_fetch_array example
  • Example#1929 - pg_fetch_assoc example
  • Example#1930 - pg_fetch_object example
  • Example#1931 - pg_fetch_result example
  • Example#1932 - pg_fetch_row example
  • Example#1933 - pg_field_is_null example
  • Example#1934 - Getting information about fields
  • Example#1935 - Getting information about fields
  • Example#1936 - Getting information about fields
  • Example#1937 - Getting information about fields
  • Example#1938 - Getting table information about a field
  • Example#1939 - Getting information about fields
  • Example#1940 - Getting information about fields
  • Example#1941 - pg_free_result example
  • Example#1942 - PostgreSQL NOTIFY message
  • Example#1943 - PostgreSQL backend PID
  • Example#1944 - pg_get_result example
  • Example#1945 - pg_host example
  • Example#1946 - pg_insert example
  • Example#1947 - pg_last_error example
  • Example#1948 - pg_last_notice example
  • Example#1949 - pg_last_oid example
  • Example#1950 - pg_lo_close example
  • Example#1951 - pg_lo_create example
  • Example#1952 - pg_lo_export example
  • Example#1953 - pg_lo_import example
  • Example#1954 - pg_lo_open example
  • Example#1955 - pg_lo_read_all example
  • Example#1956 - pg_lo_read example
  • Example#1957 - pg_lo_seek example
  • Example#1958 - pg_lo_tell example
  • Example#1959 - pg_lo_truncate example
  • Example#1960 - pg_lo_unlink example
  • Example#1961 - pg_lo_write example
  • Example#1962 - Getting table metadata
  • Example#1963 - pg_num_fields example
  • Example#1964 - pg_num_rows example
  • Example#1965 - pg_options example
  • Example#1966 - pg_parameter_status example
  • Example#1967 - Using pg_pconnect
  • Example#1968 - pg_ping example
  • Example#1969 - pg_port example
  • Example#1970 - Using pg_prepare
  • Example#1971 - pg_put_line example
  • Example#1972 - Using pg_query_params
  • Example#1973 - pg_query example
  • Example#1974 - Using pg_query with multiple statements
  • Example#1975 - pg_result_error_field example
  • Example#1976 - pg_result_error example
  • Example#1977 - pg_result_seek example
  • Example#1978 - pg_result_status example
  • Example#1979 - pg_select example
  • Example#1980 - Using pg_send_execute
  • Example#1981 - Using pg_send_prepare
  • Example#1982 - Using pg_send_query_params
  • Example#1983 - pg_send_query example
  • Example#1984 - pg_set_client_encoding example
  • Example#1985 - pg_set_error_context_visibility example
  • Example#1986 - pg_set_error_verbosity example
  • Example#1987 - pg_trace example
  • Example#1988 - pg_transaction_status example
  • Example#1989 - pg_tty example
  • Example#1990 - pg_unescape_bytea example
  • Example#1991 - pg_untrace example
  • Example#1992 - pg_update example
  • Example#1993 - pg_version example
  • Example#1994 - Backup an existing database
  • Example#1995 - SQLite3::changes example
  • Example#1996 - SQLite3::close example
  • Example#1997 - SQLite3::__construct example
  • Example#1998 - max_length aggregation function example
  • Example#1999 - SQLite3::createCollation example
  • Example#2000 - SQLite3::createFunction example
  • Example#2001 - SQLite3::enableExceptions example
  • Example#2002 - SQLite3::exec example
  • Example#2003 - SQLite3::loadExtension example
  • Example#2004 - SQLite3::open example
  • Example#2005 - SQLite3::openBlob example
  • Example#2006 - Incrementally writing a BLOB
  • Example#2007 - SQLite3::prepare example
  • Example#2008 - SQLite3::query example
  • Example#2009 - SQLite3::querySingle example
  • Example#2010 - SQLite3::setAuthorizer example
  • Example#2011 - SQLite3::version example
  • Example#2012 - SQLite3Stmt::bindParam Usage
  • Example#2013 - SQLite3Stmt::bindValue example
  • Example#2014 - Inspecting the expanded SQL
  • Example#2015 - sqlsrv_begin_transaction example
  • Example#2016 - sqlsrv_cancel example
  • Example#2017 - sqlsrv_client_info example
  • Example#2018 - sqlsrv_close example
  • Example#2019 - sqlsrv_commit example
  • Example#2020 - Connect using Windows Authentication.
  • Example#2021 - Connect by specifying a user name and password.
  • Example#2022 - Connect on a specified port.
  • Example#2023 - functionname example
  • Example#2024 - sqlsrv_execute example
  • Example#2025 - Retrieving an associative array.
  • Example#2026 - Retrieving a numeric array.
  • Example#2027 - sqlsrv_fetch_object example
  • Example#2028 - sqlsrv_fetch example
  • Example#2029 - sqlsrv_field_metadata example
  • Example#2030 - sqlsrv_free_stmt example
  • Example#2031 - sqlsrv_get_field example
  • Example#2032 - sqlsrv_has_rows example
  • Example#2033 - sqlsrv_next_result example
  • Example#2034 - sqlsrv_num_fields example
  • Example#2035 - sqlsrv_num_rows example
  • Example#2036 - sqlsrv_prepare example
  • Example#2037 - sqlsrv_query example
  • Example#2038 - sqlsrv_rollback example
  • Example#2039 - sqlsrv_rows_affected example
  • Example#2040 - sqlsrv_send_stream_data example
  • Example#2041 - sqlsrv_server_info example
  • Example#2042 - cal_days_in_month example
  • Example#2043 - cal_from_jd example
  • Example#2044 - cal_info example
  • Example#2045 - easter_date example
  • Example#2046 - Using easter_date with DateTime
  • Example#2047 - easter_days example
  • Example#2048 - Calendar functions
  • Example#2049 - Overflow behavior
  • Example#2050 - jdtojewish Example
  • Example#2051 - DateTimeImmutable::add/sub add intervals which cover elapsed time
  • Example#2052 - DateTimeImmutable::modify and strtotime increment or decrement individual component values
  • Example#2053 - Adding or subtracting times can over- or underflow dates
  • Example#2054 - Creating a mutable date time object
  • Example#2055 - Creating a mutable date time object
  • Example#2056 - DateTime::modify example
  • Example#2057 - Beware when adding or subtracting months
  • Example#2058 - All formats of Date and Time are supported
  • Example#2059 - DateTime::setTimeZone example
  • Example#2060 - DateTimeImmutable::add example
  • Example#2061 - Further DateTimeImmutable::add examples
  • Example#2062 - Beware when adding months
  • Example#2063 - DateTimeImmutable::__construct example
  • Example#2064 - Intricacies of DateTimeImmutable::__construct
  • Example#2065 - Changing the associated timezone
  • Example#2066 - Using a relative date/time string
  • Example#2067 - DateTimeImmutable::createFromFormat example
  • Example#2068 - Using predefined format constants with DateTimeImmutable::createFromFormat
  • Example#2069 - Intricacies of DateTimeImmutable::createFromFormat
  • Example#2070 - Format string with literal characters
  • Example#2071 - Overflow behaviour
  • Example#2072 - Overflowing day name behaviour
  • Example#2073 - Detecting overflown dates
  • Example#2074 - Greedy parsing behaviour
  • Example#2075 - Creating an immutable date time object
  • Example#2076 - Creating an immutable date time object
  • Example#2077 - DateTimeImmutable::getLastErrors example
  • Example#2078 - DateTimeImmutable::modify example
  • Example#2079 - Beware when adding or subtracting months
  • Example#2080 - DateTimeImmutable::setDate example
  • Example#2081 - Values exceeding ranges are added to their parent values
  • Example#2082 - DateTimeImmutable::setISODate example
  • Example#2083 - Values exceeding ranges are added to their parent values
  • Example#2084 - Finding the month a week is in
  • Example#2085 - DateTimeImmutable::setTime example
  • Example#2086 - Values exceeding ranges are added to their parent values
  • Example#2087 - DateTimeImmutable::setTimestamp example
  • Example#2088 - DateTimeImmutable::setTimeZone example
  • Example#2089 - DateTimeImmutable::sub example
  • Example#2090 - Further DateTimeImmutable::sub examples
  • Example#2091 - Beware when subtracting months
  • Example#2092 - DateTimeImmutable::diff example
  • Example#2093 - DateTimeInterface::diff during DST changeover
  • Example#2094 - DateTimeInterface::diff range
  • Example#2095 - DateTime object comparison
  • Example#2096 - DateTimeInterface::format example
  • Example#2097 - More examples
  • Example#2098 - Escaping characters while formatting
  • Example#2099 - DateTime::getOffset example
  • Example#2100 - DateTime::getTimestamp example
  • Example#2101 - Retrieving timestamp with milli and microsecond resolution
  • Example#2102 - DateTime::getTimezone example
  • Example#2103 - Creating and attaching DateTimeZone to a DateTimeImmutable
  • Example#2104 - Catching errors when instantiating DateTimeZone
  • Example#2105 - DateTimeZone::getLocation example
  • Example#2106 - DateTimeZone::getOffset examples
  • Example#2107 - A timezone_transitions_get example
  • Example#2108 - A timezone_transitions_get example with timestampBegin set
  • Example#2109 - A timezone_abbreviations_list example
  • Example#2110 - A DateTimeZone::listIdentifiers example
  • Example#2111 - Listing identifiers for a specific region
  • Example#2112 - Listing identifiers for multiple regions
  • Example#2113 - Listing identifiers for a single country
  • Example#2114 - Constructing and using DateInterval objects
  • Example#2115 - DateInterval example
  • Example#2116 - Parsing valid date intervals
  • Example#2117 - Parsing combinations and negative intervals
  • Example#2118 - Parsing special relative date intervals
  • Example#2119 - DateInterval example
  • Example#2120 - DateInterval and carry over points
  • Example#2121 - DateInterval and DateTime::diff with the %a and %d modifiers
  • Example#2122 -
  • Example#2123 - DatePeriod example
  • Example#2124 - DatePeriod example with DatePeriod::EXCLUDE_START_DATE
  • Example#2125 - DatePeriod example showing all last Thursdays in a year
  • Example#2126 - DatePeriod::createFromISO8601String example
  • Example#2127 - DatePeriod::getDateInterval example
  • Example#2128 - DatePeriod::getEndDate example
  • Example#2129 - DatePeriod::getEndDate without an end date
  • Example#2130 - Different values for DatePeriod::getRecurrences
  • Example#2131 - DatePeriod::getStartDate example
  • Example#2132 - checkdate example
  • Example#2133 - Getting the default timezone
  • Example#2134 - Getting the abbreviation of a timezone
  • Example#2135 - Getting the default timezone
  • Example#2136 - date_parse_from_format example
  • Example#2137 - date_parse_from_format with warnings example
  • Example#2138 - date_parse_from_format with errors example
  • Example#2139 - A date_parse example with a comprehensive datetime string
  • Example#2140 - date_parse with timezone abbreviation information
  • Example#2141 - date_parse with timezone identifier information
  • Example#2142 - date_parse with a minimal string
  • Example#2143 - date_parse with relative formats
  • Example#2144 - date_parse with side-effects
  • Example#2145 - A date_sun_info example
  • Example#2146 - Polar night, with some processing
  • Example#2147 - Midnight sun (Tromsø, Norway)
  • Example#2148 - Calculating length of day (Kyiv)
  • Example#2149 - date_sunrise example
  • Example#2150 - No sunrise
  • Example#2151 - date_sunset example
  • Example#2152 - No sunset
  • Example#2153 - date examples
  • Example#2154 - Escaping characters in date
  • Example#2155 - date and mktime example
  • Example#2156 - date Formatting
  • Example#2157 - getdate example
  • Example#2158 - gettimeofday example
  • Example#2159 - gmdate example
  • Example#2160 - gmmktime basic example
  • Example#2161 - gmstrftime example
  • Example#2162 - idate example
  • Example#2163 - localtime example
  • Example#2164 - Timing script execution
  • Example#2165 - microtime and REQUEST_TIME_FLOAT
  • Example#2166 - mktime basic example
  • Example#2167 - mktime example
  • Example#2168 - Last day of a month
  • Example#2169 - strftime locale examples
  • Example#2170 - ISO 8601:1988 week number example
  • Example#2171 - Cross platform compatible example using the %e modifier
  • Example#2172 - Display all known and unknown formats.
  • Example#2173 - strptime example
  • Example#2174 - A strtotime example
  • Example#2175 - Checking for failure
  • Example#2176 - time example
  • Example#2177 - A timezone_name_from_abbr example
  • Example#2178 - Getting the timezonedb version
  • Example#2179 -
  • Example#2180 -
  • Example#2181 - Measure several code blocks execution and get the total
  • Example#2182 - Closing an open file descriptor
  • Example#2183 - Setting and clearing a lock
  • Example#2184 - Opening a file descriptor
  • Example#2185 - Positioning in a file
  • Example#2186 - Setting the baud rate on a serial port
  • Example#2187 - chdir example
  • Example#2188 - chroot example
  • Example#2189 - closedir example
  • Example#2190 - dir example
  • Example#2191 - getcwd example
  • Example#2192 - opendir example
  • Example#2193 - List all entries in a directory
  • Example#2194 - List all entries in the current directory and strip out . and ..
  • Example#2195 - A simple scandir example
  • Example#2196 - A finfo_buffer example
  • Example#2197 - A finfo_file example
  • Example#2198 - Object-oriented style
  • Example#2199 - Procedural style
  • Example#2200 - mime_content_type Example
  • Example#2201 - basename example
  • Example#2202 - Changing a file's group
  • Example#2203 - Simple chown usage
  • Example#2204 - clearstatcache example
  • Example#2205 - copy example
  • Example#2206 - dirname example
  • Example#2207 - disk_free_space example
  • Example#2208 - disk_total_space example
  • Example#2209 - A simple fclose example
  • Example#2210 - fdatasync example
  • Example#2211 - Handling timeouts with feof
  • Example#2212 - feof example with an invalid file pointer
  • Example#2213 - File write example using fflush
  • Example#2214 - A fgetc example
  • Example#2215 - Read and print the entire contents of a CSV file
  • Example#2216 - Reading a file line by line
  • Example#2217 - Reading a PHP file line-by-line
  • Example#2218 - Testing whether a file exists
  • Example#2219 - Get and output the source of the homepage of a website
  • Example#2220 - Searching within the include_path
  • Example#2221 - Reading a section of a file
  • Example#2222 - Using stream contexts
  • Example#2223 - Simple usage example
  • Example#2224 - Using flags
  • Example#2225 - file example
  • Example#2226 - fileatime example
  • Example#2227 - A filectime example
  • Example#2228 - Finding the group of a file
  • Example#2229 - Comparing the inode of a file with the current file
  • Example#2230 - filemtime example
  • Example#2231 - Finding the owner of a file
  • Example#2232 - Display permissions as an octal value
  • Example#2233 - Display full permissions
  • Example#2234 - filesize example
  • Example#2235 - filetype example
  • Example#2236 - flock example
  • Example#2237 - flock using the LOCK_NB option
  • Example#2238 - Checking a color name against a shell wildcard pattern
  • Example#2239 - fopen examples
  • Example#2240 - Using fpassthru with binary files
  • Example#2241 - fputcsv example
  • Example#2242 - A simple fread example
  • Example#2243 - Binary fread example
  • Example#2244 - Remote fread examples
  • Example#2245 - fscanf Example
  • Example#2246 - Contents of users.txt
  • Example#2247 - fseek example
  • Example#2248 - fstat example
  • Example#2249 - fsync example
  • Example#2250 - ftell example
  • Example#2251 - File truncation example
  • Example#2252 - A simple fwrite example
  • Example#2253 - Convenient way how glob can replace opendir and friends.
  • Example#2254 - is_dir example
  • Example#2255 - is_executable example
  • Example#2256 - is_file example
  • Example#2257 - Create and confirm if a file is a symbolic link
  • Example#2258 - is_readable example
  • Example#2259 - is_uploaded_file example
  • Example#2260 - is_writable example
  • Example#2261 - Changing the group of a symbolic link
  • Example#2262 - Changing the owner of a symbolic link
  • Example#2263 - Creating a simple hard link
  • Example#2264 - linkinfo example
  • Example#2265 - Comparison of stat and lstat
  • Example#2266 - mkdir example
  • Example#2267 - mkdir using the recursive parameter
  • Example#2268 - Uploading multiple files
  • Example#2269 - Contents of sample.ini
  • Example#2270 - parse_ini_file example
  • Example#2271 - parse_ini_file parsing a php.ini file
  • Example#2272 - Value Interpolation
  • Example#2273 - Escaping Characters
  • Example#2274 - pathinfo Example
  • Example#2275 - pathinfo example showing difference between null and no extension
  • Example#2276 - pathinfo example for a dot-file
  • Example#2277 - pathinfo example with array dereferencing
  • Example#2278 - pclose example
  • Example#2279 - popen example
  • Example#2280 - popen example
  • Example#2281 - Forcing a download using readfile
  • Example#2282 - readlink example
  • Example#2283 - realpath_cache_get example
  • Example#2284 - realpath_cache_size example
  • Example#2285 - realpath example
  • Example#2286 - realpath on Windows
  • Example#2287 - Example with rename
  • Example#2288 - rewind overwriting example
  • Example#2289 - rmdir example
  • Example#2290 - stat example
  • Example#2291 - Using stat information together with touch
  • Example#2292 - Create a symbolic link
  • Example#2293 - tempnam example
  • Example#2294 - tmpfile example
  • Example#2295 - touch example
  • Example#2296 - touch using the mtime parameter
  • Example#2297 - umask example
  • Example#2298 - Basic unlink usage
  • Example#2299 - Example usage of inotify
  • Example#2300 - Checks if system administrator has signed the file
  • Example#2301 - Prints names of all extended attributes of file
  • Example#2302 - Removes all extended attributes of a file
  • Example#2303 - Sets extended attributes on .wav file
  • Example#2304 - xattr_supported example
  • Example#2305 - xdiff_file_bdiff_size example
  • Example#2306 - xdiff_file_bdiff example
  • Example#2307 - xdiff_file_bpatch example
  • Example#2308 - xdiff_file_diff_binary example
  • Example#2309 - xdiff_file_diff example
  • Example#2310 - xdiff_file_merge3 example
  • Example#2311 - xdiff_file_patch_binary example
  • Example#2312 - xdiff_file_patch example
  • Example#2313 - Patch reversing example
  • Example#2314 - xdiff_file_rabdiff example
  • Example#2315 - xdiff_string_bdiff_size example
  • Example#2316 - xdiff_string_diff example
  • Example#2317 - xdiff_string_patch example
  • Example#2318 - Enchant Usage Example
  • Example#2319 - List the backends provided by the given broker
  • Example#2320 - A enchant_broker_dict_exists example
  • Example#2321 - List all available dictionaries for one broker
  • Example#2322 - A enchant_broker_request_dict example
  • Example#2323 - Adding a word to a PWL
  • Example#2324 - A enchant_dict_describe example
  • Example#2325 - A enchant_dict_quick_check example
  • Example#2326 - A enchant_dict_suggest example
  • Example#2327 - Usage example.
  • Example#2328 - Using Gender\Gender::country
  • Example#2329 - bindtextdomain example
  • Example#2330 - gettext-check
  • Example#2331 - ngettext example
  • Example#2332 - iconv_get_encoding example
  • Example#2333 - iconv_mime_decode_headers example
  • Example#2334 - iconv_mime_decode example
  • Example#2335 - iconv_mime_encode example
  • Example#2336 - iconv_set_encoding example
  • Example#2337 - iconv example
  • Example#2338 - ob_iconv_handler example:
  • Example#2339 - Example of using the procedural API
  • Example#2340 - Example of using the object-oriented API
  • Example#2341 - FRENCH_COLLATION rules
  • Example#2342 - ALTERNATE_HANDLING rules
  • Example#2343 - CASE_FIRST rules
  • Example#2344 - CASE_LEVEL rules
  • Example#2345 - collator_asort example
  • Example#2346 - collator_compare example
  • Example#2347 - Comparing strings without diacritics or case-sensitivity
  • Example#2348 - Collator::__construct example
  • Example#2349 - collator_create example
  • Example#2350 - collator_get_attribute example
  • Example#2351 - collator_get_error_code example
  • Example#2352 - collator_get_error_message example
  • Example#2353 - collator_get_locale example
  • Example#2354 - collator_get_sort_keyexample
  • Example#2355 - collator_get_strength example
  • Example#2356 - collator_set_attribute example
  • Example#2357 - collator_set_strength example
  • Example#2358 - collator_sort_with_sort_keys example
  • Example#2359 - collator_sort example
  • Example#2360 - numfmt_create example
  • Example#2361 - NumberFormatter::create example
  • Example#2362 - numfmt_format_currency example
  • Example#2363 - OO example
  • Example#2364 - numfmt_format example
  • Example#2365 - OO example
  • Example#2366 - numfmt_get_attribute example
  • Example#2367 - OO example
  • Example#2368 - numfmt_get_error_code example
  • Example#2369 - OO example
  • Example#2370 - numfmt_get_error_message example
  • Example#2371 - OO example
  • Example#2372 - numfmt_get_locale example
  • Example#2373 - numfmt_get_pattern example
  • Example#2374 - OO example
  • Example#2375 - numfmt_get_symbol example
  • Example#2376 - OO example
  • Example#2377 - numfmt_get_text_attribute example
  • Example#2378 - OO example
  • Example#2379 - numfmt_parse_currency example
  • Example#2380 - OO example
  • Example#2381 - numfmt_parse example
  • Example#2382 - OO example
  • Example#2383 - numfmt_set_attribute example
  • Example#2384 - OO example
  • Example#2385 - numfmt_set_pattern example
  • Example#2386 - OO example
  • Example#2387 - numfmt_set_symbol example
  • Example#2388 - OO example
  • Example#2389 - numfmt_set_text_attribute example
  • Example#2390 - OO example
  • Example#2391 - locale_accept_from_http example
  • Example#2392 - OO example
  • Example#2393 - locale_compose example
  • Example#2394 - OO example
  • Example#2395 - Subtag limits
  • Example#2396 - locale_filter_matches example
  • Example#2397 - OO example
  • Example#2398 - locale_get_all_variants example
  • Example#2399 - OO example
  • Example#2400 - locale_get_default example
  • Example#2401 - OO example
  • Example#2402 - locale_get_display_language example
  • Example#2403 - OO example
  • Example#2404 - locale_get_display_name example
  • Example#2405 - OO example
  • Example#2406 - locale_get_display_region example
  • Example#2407 - OO example
  • Example#2408 - locale_get_display_script example
  • Example#2409 - OO example
  • Example#2410 - locale_get_display_variant example
  • Example#2411 - OO example
  • Example#2412 - locale_get_keywords example
  • Example#2413 - OO example
  • Example#2414 - locale_get_primary_language example
  • Example#2415 - OO example
  • Example#2416 - locale_get_region example
  • Example#2417 - OO example
  • Example#2418 - locale_get_script example
  • Example#2419 - OO example
  • Example#2420 - locale_lookup example
  • Example#2421 - OO example
  • Example#2422 - locale_parse example
  • Example#2423 - OO example
  • Example#2424 - locale_set_default example
  • Example#2425 - OO example
  • Example#2426 - Normalizer::getRawDecomposition example
  • Example#2427 - normalizer_is_normalized example
  • Example#2428 - OO example
  • Example#2429 - normalizer_normalize example
  • Example#2430 - OO example
  • Example#2431 - msgfmt_create example
  • Example#2432 - OO example
  • Example#2433 - msgfmt_format_message example
  • Example#2434 - OO example
  • Example#2435 - Instructing ICU to format currency with common and with narrow currency symbol
  • Example#2436 - msgfmt_format example
  • Example#2437 - OO example
  • Example#2438 - msgfmt_get_error_message example
  • Example#2439 - OO example
  • Example#2440 - msgfmt_get_locale example
  • Example#2441 - OO example
  • Example#2442 - msgfmt_get_pattern example
  • Example#2443 - OO example
  • Example#2444 - msgfmt_parse_message example
  • Example#2445 - OO example
  • Example#2446 - msgfmt_parse example
  • Example#2447 - OO example
  • Example#2448 - msgfmt_set_pattern example
  • Example#2449 - OO example
  • Example#2450 - IntlCalendar::add
  • Example#2451 - IntlCalendar::after
  • Example#2452 - IntlCalendar::clear examples
  • Example#2453 - IntlCalendar::createInstance
  • Example#2454 - IntlCalendar::equals
  • Example#2455 - IntlCalendar::fieldDifference
  • Example#2456 - IntlCalendar::fromDateTime
  • Example#2457 - IntlCalendar::get
  • Example#2458 - IntlCalendar::getActualMaximum
  • Example#2459 - IntlCalendar::getAvailableLocales
  • Example#2460 - IntlCalendar::getDayOfWeekType
  • Example#2461 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2462 - IntlCalendar::getErrorMessage
  • Example#2463 - IntlCalendar::getFirstDayOfWeek
  • Example#2464 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2465 - Maxima examples
  • Example#2466 - IntlCalendar::getLocale
  • Example#2467 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2468 - IntlCalendar::getNow
  • Example#2469 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2470 - IntlCalendar::getSkippedWallTimeOption
  • Example#2471 - IntlCalendar::getTime
  • Example#2472 - IntlCalendar::getTimeZone
  • Example#2473 - IntlCalendar::getType
  • Example#2474 - IntlCalendar::inDaylightTime
  • Example#2475 - IntlCalendar::isEquivalentTo
  • Example#2476 - IntlCalendar::isLenient
  • Example#2477 - IntlCalendar::isWeekend
  • Example#2478 - IntlCalendar::roll
  • Example#2479 - IntlCalendar::set
  • Example#2480 - IntlCalendar::setDate example
  • Example#2481 - IntlCalendar::setDateTime example
  • Example#2482 - IntlCalendar::setFirstDayOfWeek
  • Example#2483 - IntlCalendar::setTime
  • Example#2484 - IntlCalendar::setTimeZone
  • Example#2485 - IntlCalendar::toDateTime
  • Example#2486 - IntlGregorianCalendar::createFromDate example
  • Example#2487 - IntlCalendar::setDateTime example
  • Example#2488 - datefmt_create example
  • Example#2489 - OO example
  • Example#2490 - Example of invalid locale handling
  • Example#2491 - datefmt_format example
  • Example#2492 - OO example
  • Example#2493 - With IntlCalendar object
  • Example#2494 - IntlDateFormatter::formatObject examples
  • Example#2495 - datefmt_get_calendar example
  • Example#2496 - OO example
  • Example#2497 - Example of invalid locale handling
  • Example#2498 - datefmt_get_datetype example
  • Example#2499 - OO example
  • Example#2500 - datefmt_get_error_code example
  • Example#2501 - OO example
  • Example#2502 - datefmt_get_error_message example
  • Example#2503 - OO example
  • Example#2504 - datefmt_get_locale example
  • Example#2505 - OO example
  • Example#2506 - datefmt_get_pattern example
  • Example#2507 - OO example
  • Example#2508 - datefmt_get_timetype example
  • Example#2509 - OO example
  • Example#2510 - datefmt_get_timezone_id example
  • Example#2511 - OO example
  • Example#2512 - IntlDateFormatter::getCalendarObject example
  • Example#2513 - IntlDateFormatter::getTimeZone examples
  • Example#2514 - datefmt_is_lenient example
  • Example#2515 - OO example
  • Example#2516 - datefmt_localtime example
  • Example#2517 - OO example
  • Example#2518 - OO example
  • Example#2519 - datefmt_parse example
  • Example#2520 - datefmt_set_calendar example
  • Example#2521 - OO example
  • Example#2522 - Example with IntlCalendar argument
  • Example#2523 - datefmt_set_lenient example
  • Example#2524 - OO example
  • Example#2525 - datefmt_set_pattern example
  • Example#2526 - OO example
  • Example#2527 - IntlDateFormatter::setTimeZone examples
  • Example#2528 - resourcebundle_count example
  • Example#2529 - OO example
  • Example#2530 - resourcebundle_create example
  • Example#2531 - ResourceBundle::create example
  • Example#2532 - resourcebundle_get_error_code example
  • Example#2533 - OO example
  • Example#2534 - resourcebundle_get_error_message example
  • Example#2535 - OO example
  • Example#2536 - resourcebundle_get example
  • Example#2537 - OO example
  • Example#2538 - resourcebundle_locales example
  • Example#2539 - OO example
  • Example#2540 - Spoofchecker::areConfusable example
  • Example#2541 - Spoofchecker::isSuspicious example
  • Example#2542 - Retrieving the registered transliterator IDs
  • Example#2543 - Converting escaped UTF-16 code units
  • Example#2544 - IntlDatePatternGenerator::getBestPattern example
  • Example#2545 - Converting from UTF-8 to UTF-16 and back
  • Example#2546 - Invalid characters in input
  • Example#2547 - Characters which cannot be encoded
  • Example#2548 - grapheme_extract example
  • Example#2549 - grapheme_stripos example
  • Example#2550 - grapheme_stristr example
  • Example#2551 - grapheme_strlen example
  • Example#2552 - grapheme_strpos example
  • Example#2553 - grapheme_strripos example
  • Example#2554 - grapheme_strrpos example
  • Example#2555 - grapheme_strstr example
  • Example#2556 - grapheme_substr example
  • Example#2557 - idn_to_ascii example
  • Example#2558 - idn_to_utf8 example
  • Example#2559 - Testing different code points
  • Example#2560 - Testing different code points
  • Example#2561 - Testing different code points
  • Example#2562 - Testing different code points
  • Example#2563 - Testing different code points
  • Example#2564 - Testing different code points
  • Example#2565 - Testing different code points
  • Example#2566 - Testing different code points
  • Example#2567 - Testing different code points
  • Example#2568 - Enumerating over a sample range of code points
  • Example#2569 - Enumerating over a sample range of code points
  • Example#2570 - Testing different code points
  • Example#2571 - Testing different code points
  • Example#2572 - Testing different code points
  • Example#2573 - Testing different code points
  • Example#2574 - Testing different code points
  • Example#2575 - Testing different properties
  • Example#2576 - Testing different properties
  • Example#2577 - Testing different properties
  • Example#2578 - Testing different code points
  • Example#2579 - Testing different properties
  • Example#2580 - Testing different properties
  • Example#2581 - Testing different properties
  • Example#2582 - Testing different properties
  • Example#2583 - Testing different properties
  • Example#2584 - Testing different properties
  • Example#2585 - Testing different code points
  • Example#2586 - Testing different code points
  • Example#2587 - Testing different code points
  • Example#2588 - Testing different code points
  • Example#2589 - Testing different code points
  • Example#2590 - Testing different code points
  • Example#2591 - Testing different code points
  • Example#2592 - Testing different code points
  • Example#2593 - Testing different code points
  • Example#2594 - Testing different code points
  • Example#2595 - Testing different code points
  • Example#2596 - Testing different code points
  • Example#2597 - Testing different code points
  • Example#2598 - Testing different code points
  • Example#2599 - Testing different code points
  • Example#2600 - Testing different code points
  • Example#2601 - Testing different code points
  • Example#2602 - Testing different code points
  • Example#2603 - Testing different code points
  • Example#2604 - Testing different code points
  • Example#2605 - Testing different code points
  • Example#2606 - Testing different code points
  • Example#2607 - Testing different code points
  • Example#2608 - Testing different code points
  • Example#2609 - Testing different code points
  • Example#2610 - Testing different code points
  • Example#2611 - Testing different code points
  • Example#2612 - Testing different code points
  • Example#2613 - Testing different code points
  • Example#2614 - Testing different code points
  • Example#2615 - Testing different code points
  • Example#2616 - Testing different code points
  • Example#2617 - intl_error_name example
  • Example#2618 - intl_get_error_code example
  • Example#2619 - intl_get_error_message example
  • Example#2620 - intl_is_failure example
  • Example#2621 - php.ini setting examples
  • Example#2622 - php.ini setting for EUC-JP users
  • Example#2623 - php.ini setting for SJIS users
  • Example#2624 - Disable HTTP input conversion in php.ini
  • Example#2625 - php.ini setting example
  • Example#2626 - Script example
  • Example#2627 - Testing different code points
  • Example#2628 - mb_convert_case example
  • Example#2629 - mb_convert_case example with non-Latin UTF-8 text
  • Example#2630 - mb_convert_encoding example
  • Example#2631 - mb_convert_kana example
  • Example#2632 - mb_convert_variables example
  • Example#2633 - map example
  • Example#2634 - map example escapes JavaScript string
  • Example#2635 - mb_detect_encoding example
  • Example#2636 - Effect of strict parameter
  • Example#2637 - Effect of order when multiple encodings match
  • Example#2638 - mb_detect_order examples
  • Example#2639 - Example showing useless detect orders
  • Example#2640 - mb_encode_mimeheader example
  • Example#2641 - map example
  • Example#2642 - mb_encode_numericentity example
  • Example#2643 - mb_encoding_aliases example
  • Example#2644 - mb_ereg_replace_callback example
  • Example#2645 - mb_ereg_replace_callback using anonymous function
  • Example#2646 - mb_internal_encoding example
  • Example#2647 - mb_list_encodings example
  • Example#2648 -
  • Example#2649 - mb_output_handler example
  • Example#2650 - mb_preferred_mime_name example
  • Example#2651 - mb_str_pad example
  • Example#2652 - mb_strimwidth example
  • Example#2653 - mb_strtolower example
  • Example#2654 - mb_strtolower example with non-Latin UTF-8 text
  • Example#2655 - mb_strtoupper example
  • Example#2656 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#2657 - mb_strwidth example
  • Example#2658 - mb_substitute_character example
  • Example#2659 - mb_substr_count example
  • Example#2660 - pspell_add_to_personal
  • Example#2661 - pspell_check Example
  • Example#2662 - pspell_add_to_personal Example
  • Example#2663 - pspell_config_create
  • Example#2664 - pspell_config_ignore
  • Example#2665 - pspell_config_mode Example
  • Example#2666 - pspell_config_personal
  • Example#2667 - pspell_config_repl
  • Example#2668 - pspell_config_runtogether
  • Example#2669 - pspell_new_config
  • Example#2670 - pspell_new_personal
  • Example#2671 - pspell_new
  • Example#2672 - pspell_add_to_personal
  • Example#2673 - pspell_store_replacement
  • Example#2674 - pspell_suggest example
  • Example#2675 - Basic recode_file example
  • Example#2676 - Basic recode_string example
  • Example#2677 - exif_imagetype example
  • Example#2678 - exif_read_data example
  • Example#2679 - exif_read_data with streams available as of PHP 7.2.0
  • Example#2680 - exif_tagname example
  • Example#2681 - exif_thumbnail example
  • Example#2682 - PNG creation with PHP
  • Example#2683 - Adding watermarks to images using alpha channels
  • Example#2684 - Using imagecopymerge to create a translucent watermark
  • Example#2685 - Using gd_info
  • Example#2686 - getimagesize and MIME types
  • Example#2687 - getimagesize example
  • Example#2688 - getimagesize (URL)
  • Example#2689 - getimagesize() returning IPTC
  • Example#2690 - getimagesizefromstring example
  • Example#2691 - image_type_to_extension example
  • Example#2692 - image_type_to_mime_type example
  • Example#2693 - image2wbmp example
  • Example#2694 - imageaffinematrixconcat example
  • Example#2695 - imageaffinematrixget example
  • Example#2696 - imagealphablending usage example
  • Example#2697 - A comparison of two lines, one with anti-aliasing switched on
  • Example#2698 - Drawing a circle with imagearc
  • Example#2699 - Saving a BMP file
  • Example#2700 - imagechar example
  • Example#2701 - imagecharup example
  • Example#2702 - imagecolorallocate example
  • Example#2703 - Example of using imagecolorallocatealpha
  • Example#2704 - Convert typical alpha values for use with imagecolorallocatealpha
  • Example#2705 - Access distinct RGB values
  • Example#2706 - Human-readable RGB values using imagecolorsforindex
  • Example#2707 - Search for a set of colors in an image
  • Example#2708 - Search for a set of colors in an image
  • Example#2709 - Example of using imagecolorclosesthwb
  • Example#2710 - Using imagecolordeallocate
  • Example#2711 - Get colors from the GD logo
  • Example#2712 - Get colors from the GD logo
  • Example#2713 - imagecolormatch example
  • Example#2714 - Using imagecoloresolve to get colors from an image
  • Example#2715 - Using imagecoloresolvealpha to get colors from an image
  • Example#2716 - imagecolorset example
  • Example#2717 - imagecolorsforindex example
  • Example#2718 - Getting total number of colors in an image using imagecolorstotal
  • Example#2719 - imagecolortransparent example
  • Example#2720 - Embossing the PHP.net logo
  • Example#2721 - Gaussian blur
  • Example#2722 - Cropping the PHP.net logo
  • Example#2723 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#2724 - imagecopymergegray usage
  • Example#2725 - Simple example
  • Example#2726 - Resampling an image proportionally
  • Example#2727 - Resizing an image
  • Example#2728 - Creating a new GD image stream and outputting an image.
  • Example#2729 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#2730 - imagecreatefromgd2 example
  • Example#2731 - imagecreatefromgd2part example
  • Example#2732 - imagecreatefromgd example
  • Example#2733 - Example to handle an error during loading of a GIF
  • Example#2734 - Example to handle an error during loading of a JPEG
  • Example#2735 - Example to handle an error during loading of a PNG
  • Example#2736 - imagecreatefromstring example
  • Example#2737 - Example to handle an error during loading of a WBMP
  • Example#2738 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#2739 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#2740 - Creating an image instance using imagecreatefromxpm
  • Example#2741 - Creating a new GD image stream and outputting an image.
  • Example#2742 - imagecrop example
  • Example#2743 - Proper handling of auto-cropping
  • Example#2744 - imagedashedline example
  • Example#2745 - Alternative to imagedashedline
  • Example#2746 - Using imagedestroy prior to PHP 8.0.0
  • Example#2747 - imageellipse example
  • Example#2748 - imagefill example
  • Example#2749 - Creating a 3D looking pie
  • Example#2750 - imagefilledellipse example
  • Example#2751 - imagefilledpolygon example
  • Example#2752 - imagefilledrectangle usage
  • Example#2753 - Filling an ellipse with a color
  • Example#2754 - imagefilter grayscale example
  • Example#2755 - imagefilter brightness example
  • Example#2756 - imagefilter colorize example
  • Example#2757 - imagefilter negate example
  • Example#2758 - imagefilter pixelate example
  • Example#2759 - imagefilter scatter example
  • Example#2760 - Flips an image vertically
  • Example#2761 - Flips the image horizontally
  • Example#2762 - Using imagefontheight on built-in fonts
  • Example#2763 - Using imagefontheight together with imageloadfont
  • Example#2764 - Using imagefontwidth on built-in fonts
  • Example#2765 - Using imagefontwidth together with imageloadfont
  • Example#2766 - imageftbbox example
  • Example#2767 - imagefttext example
  • Example#2768 - imagegammacorrect usage
  • Example#2769 - Outputting a GD2 image
  • Example#2770 - Saving a GD2 image
  • Example#2771 - Outputting a GD image
  • Example#2772 - Saving a GD image
  • Example#2773 - imagegetclip example
  • Example#2774 - Outputting an image using imagegif
  • Example#2775 - Converting a PNG image to GIF using imagegif
  • Example#2776 - imagegrabscreen example
  • Example#2777 - imagegrabwindow example
  • Example#2778 - Turn on interlacing using imageinterlace
  • Example#2779 - Simple detection of true color image instances using imageistruecolor
  • Example#2780 - Outputting a JPEG image to the browser
  • Example#2781 - Saving a JPEG image to a file
  • Example#2782 - Outputting the image at 75% quality to the browser
  • Example#2783 - imagelayereffect example
  • Example#2784 - Drawing a thick line
  • Example#2785 - imageloadfont usage example
  • Example#2786 - imageopenpolygon example
  • Example#2787 - imagepalettecopy example
  • Example#2788 - Converts any image object to true color
  • Example#2789 - imagepolygon example
  • Example#2790 - Simple imagerectangle example
  • Example#2791 - Setting and getting the resolution of an image
  • Example#2792 - Rotate an image 180 degrees
  • Example#2793 - Basic imagesavealpha Usage
  • Example#2794 - imagesetbrush example
  • Example#2795 - imagesetinterpolation example
  • Example#2796 - imagesetpixel example
  • Example#2797 - imagesetstyle example
  • Example#2798 - imagesetthickness example
  • Example#2799 - imagesettile example
  • Example#2800 - imagestring example
  • Example#2801 - imagestringup example
  • Example#2802 - Using imagesx
  • Example#2803 - Using imagesy
  • Example#2804 - Converting a true color image to a palette-based image
  • Example#2805 - imagettfbbox example
  • Example#2806 - imagettftext example
  • Example#2807 - Checking for PNG support
  • Example#2808 - Outputting a WBMP image
  • Example#2809 - Saving the WBMP image
  • Example#2810 - Outputting the image with a different foreground
  • Example#2811 - Saving an WebP file
  • Example#2812 - Saving an XBM file
  • Example#2813 - Saving an XBM file with a different foreground color
  • Example#2814 - Embedding IPTC data into a JPEG
  • Example#2815 - iptcparse() used together with getimagesize
  • Example#2816 - jpeg2wbmp example
  • Example#2817 - png2wbmp example
  • Example#2818 - Gmagick Example
  • Example#2819 - Gmagick::despeckleimage example
  • Example#2820 - Gmagick::setCompressionQuality
  • Example#2821 - Creating a thumbnail in Imagick
  • Example#2822 - Make a thumbnail of all JPG files in a directory
  • Example#2823 - Creating a reflection of an image
  • Example#2824 - Filling text with gradient
  • Example#2825 - Read in GIF image and resize all frames
  • Example#2826 - Create a PHP logo
  • Example#2827 - Using Imagick::adaptiveBlurImage:
  • Example#2828 - Using Imagick::adaptiveResizeImage
  • Example#2829 - A Imagick::adaptiveSharpenImage example
  • Example#2830 - Imagick::adaptiveThresholdImage
  • Example#2831 - Imagick::addNoiseImage
  • Example#2832 - Imagick::affineTransformImage
  • Example#2833 - Using Imagick::annotateImage:
  • Example#2834 - Imagick::appendImages example
  • Example#2835 - Imagick::autoLevelImage
  • Example#2836 - Imagick::blackThresholdImage
  • Example#2837 - Imagick::blueShiftImage
  • Example#2838 - Using Imagick::blurImage:
  • Example#2839 - Imagick::borderImage
  • Example#2840 - Imagick::brightnessContrastImage
  • Example#2841 - Imagick::charcoalImage
  • Example#2842 - Using Imagick::chopImage:
  • Example#2843 - Imagick object cloning in different versions of imagick
  • Example#2844 - Using Imagick::clutImage:
  • Example#2845 - Imagick::colorizeImage
  • Example#2846 - Imagick::colorMatrixImage
  • Example#2847 - Using Imagick::commentImage:
  • Example#2848 - Using Imagick::compareImageLayers
  • Example#2849 - Using Imagick::compareImages:
  • Example#2850 - Using Imagick::compositeImage:
  • Example#2851 - Imagick::contrastImage
  • Example#2852 - Imagick::convolveImage
  • Example#2853 - Imagick::cropImage
  • Example#2854 - Imagick::deskewImage
  • Example#2855 - Imagick::despeckleImage
  • Example#2856 - Using Imagick::distortImage:
  • Example#2857 - Imagick::edgeImage
  • Example#2858 - Imagick::embossImage
  • Example#2859 - Imagick::enhanceImage
  • Example#2860 - Imagick::equalizeImage
  • Example#2861 - Using Imagick::evaluateImage
  • Example#2862 - Using Imagick::exportImagePixels
  • Example#2863 - Imagick::filter
  • Example#2864 - Imagick::flipImage
  • Example#2865 - Imagick::floodfillPaintImage example
  • Example#2866 - Imagick::flopImage
  • Example#2867 - Imagick::forwardFourierTransformImage
  • Example#2868 - Imagick::frameImage
  • Example#2869 - Create a sinusoidal gradient
  • Example#2870 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#2871 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#2872 - Imagick::fxImage
  • Example#2873 - Imagick::gammaImage
  • Example#2874 - Imagick::gaussianBlurImage
  • Example#2875 - Using Imagick::getImageGeometry
  • Example#2876 - Generates Imagick::getImageHistogram
  • Example#2877 - Using Imagick::getImageLength:
  • Example#2878 - Using Imagick::getImageProperties:
  • Example#2879 - Using Imagick::getImageProperty:
  • Example#2880 - Using Imagick::getIteratorIndex:
  • Example#2881 - Imagick::getPixelIterator
  • Example#2882 - Imagick::getPixelRegionIterator example
  • Example#2883 - Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)
  • Example#2884 - Imagick::haldClutImage
  • Example#2885 - Imagick::identifyFormat
  • Example#2886 - Example Result Format
  • Example#2887 - Imagick::implodeImage
  • Example#2888 - Imagick::importImagePixels example
  • Example#2889 - Imagick::levelImage
  • Example#2890 - Imagick::linearStretchImage
  • Example#2891 - Imagick::magnifyImage
  • Example#2892 - Imagick::medianFilterImage
  • Example#2893 - Imagick::mergeImageLayers
  • Example#2894 - Imagick::modulateImage
  • Example#2895 - Convolve Imagick::morphology
  • Example#2896 - Correlate Imagick::morphology
  • Example#2897 - Erode Imagick::morphology
  • Example#2898 - Erode Intensity Imagick::morphology
  • Example#2899 - Dilate Imagick::morphology
  • Example#2900 - Dilate intensity Imagick::morphology
  • Example#2901 - Distance with Chebyshev kernel Imagick::morphology
  • Example#2902 - Distance with Manhattan kernel Imagick::morphology
  • Example#2903 - Distance with ocatagonal kernel Imagick::morphology
  • Example#2904 - Distance with Euclidean kernel Imagick::morphology
  • Example#2905 - Edge Imagick::morphology
  • Example#2906 - Open Imagick::morphology
  • Example#2907 - Open intensity Imagick::morphology
  • Example#2908 - Close Imagick::morphology
  • Example#2909 - Close Intensity Imagick::morphology
  • Example#2910 - Smooth Imagick::morphology
  • Example#2911 - Edge in Imagick::morphology
  • Example#2912 - Edge out Imagick::morphology
  • Example#2913 - 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#2914 - 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#2915 - Hit and Miss Imagick::morphology
  • Example#2916 - Thinning Imagick::morphology
  • Example#2917 - Thicken Imagick::morphology
  • Example#2918 - Thick to generate a convex hull Imagick::morphology
  • Example#2919 - Iterative morphology Imagick::morphology
  • Example#2920 - Helper function to get an image silhouette Imagick::morphology
  • Example#2921 - Imagick::motionBlurImage
  • Example#2922 - Imagick::negateImage
  • Example#2923 - Using Imagick::newImage:
  • Example#2924 - Imagick::newPseudoImage
  • Example#2925 - Imagick::normalizeImage
  • Example#2926 - Imagick::oilPaintImage
  • Example#2927 - Using Imagick::optimizeImageLayers
  • Example#2928 - Imagick::orderedPosterizeImage
  • Example#2929 - Using Imagick::pingImageBlob
  • Example#2930 - Using Imagick::pingImageFile
  • Example#2931 - A Imagick::polaroidImage example
  • Example#2932 - Imagick::posterizeImage
  • Example#2933 - Imagick::quantizeImage
  • Example#2934 - Using Imagick::queryFontMetrics:
  • Example#2935 - Imagick::queryFonts
  • Example#2936 - Imagick::queryFormats
  • Example#2937 - Imagick::radialBlurImage
  • Example#2938 - Imagick::raiseImage
  • Example#2939 - Imagick::randomThresholdImage
  • Example#2940 - Imagick::readImageBlob
  • Example#2941 - Imagick::recolorImage
  • Example#2942 - Imagick::reduceNoiseImage
  • Example#2943 - Imagick::resampleImage
  • Example#2944 - Imagick::resizeImage
  • Example#2945 - Imagick::rollImage
  • Example#2946 - Imagick::rotateImage
  • Example#2947 - Imagick::rotationalBlurImage
  • Example#2948 - Using Imagick::roundCorners:
  • Example#2949 - Imagick::scaleImage
  • Example#2950 - Imagick::segmentImage
  • Example#2951 - Imagick::selectiveBlurImage
  • Example#2952 - Imagick::separateImageChannel
  • Example#2953 - Imagick::sepiaToneImage
  • Example#2954 - Imagick::setCompressionQuality
  • Example#2955 - A Imagick::setFont example
  • Example#2956 - A Imagick::setImage example
  • Example#2957 - Imagick::setImageArtifact
  • Example#2958 - Imagick::setImageBias
  • Example#2959 - Imagick::setImageClipMask
  • Example#2960 - Imagick::setImageCompressionQuality
  • Example#2961 - Modify animated Gif with Imagick::setImageDelay
  • Example#2962 - Basic Imagick::setImageIterations usage
  • Example#2963 - A Imagick::setImageOpacity example
  • Example#2964 - Imagick::setImageOrientation
  • Example#2965 - Using Imagick::setImageProperty:
  • Example#2966 - Imagick::setImageResolution
  • Example#2967 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#2968 - Using Imagick::setIteratorIndex:
  • Example#2969 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#2970 - Imagick::setOption
  • Example#2971 - Imagick::setOption
  • Example#2972 - A Imagick::setPointSize example
  • Example#2973 - Imagick::setProgressMonitor
  • Example#2974 - Imagick::setSamplingFactors
  • Example#2975 - Imagick::shadeImage
  • Example#2976 - Imagick::shadowImage
  • Example#2977 - Imagick::sharpenImage
  • Example#2978 - Imagick::shaveImage
  • Example#2979 - Imagick::shearImage
  • Example#2980 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#2981 - Imagick::sketchImage
  • Example#2982 - Imagick::smushImages
  • Example#2983 - Imagick::solarizeImage
  • Example#2984 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2985 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#2986 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#2987 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#2988 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2989 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#2990 - Imagick::spliceImage
  • Example#2991 - Imagick::spreadImage
  • Example#2992 - Imagick::statisticImage
  • Example#2993 - Imagick::subImageMatch
  • Example#2994 - Imagick::swirlImage
  • Example#2995 - Imagick::textureImage
  • Example#2996 - Imagick::thresholdImage
  • Example#2997 - Imagick::thumbnailImage
  • Example#2998 - Imagick::tintImage
  • Example#2999 - Using Imagick::transformImage:
  • Example#3000 - Imagick::transformImageColorspace example
  • Example#3001 - Imagick::transparentPaintImage
  • Example#3002 - Imagick::transposeImage
  • Example#3003 - Imagick::transverseImage
  • Example#3004 - Using Imagick::trimImage:
  • Example#3005 - Imagick::uniqueImageColors
  • Example#3006 - Imagick::unsharpMaskImage
  • Example#3007 - Imagick::vignetteImage
  • Example#3008 - WaveImage can be quite slow Imagick::waveImage
  • Example#3009 - Imagick::whiteThresholdImage
  • Example#3010 - ImagickDraw::affine example
  • Example#3011 - ImagickDraw::arc example
  • Example#3012 - ImagickDraw::bezier example
  • Example#3013 - ImagickDraw::circle example
  • Example#3014 - ImagickDraw::composite example
  • Example#3015 - ImagickDraw::ellipse example
  • Example#3016 - ImagickDraw::line example
  • Example#3017 - ImagickDraw::matte example
  • Example#3018 - ImagickDraw::pathCurveToQuadraticBezierAbsolute example
  • Example#3019 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute example
  • Example#3020 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative example
  • Example#3021 - ImagickDraw::pathStart example
  • Example#3022 - ImagickDraw::point example
  • Example#3023 - ImagickDraw::polygon example
  • Example#3024 - ImagickDraw::polyline example
  • Example#3025 - ImagickDraw::popDefs example
  • Example#3026 - ImagickDraw::push example
  • Example#3027 - ImagickDraw::pushPattern example
  • Example#3028 - ImagickDraw::rectangle example
  • Example#3029 - ImagickDraw::rotate example
  • Example#3030 - ImagickDraw::roundRectangle example
  • Example#3031 - ImagickDraw::scale example
  • Example#3032 - ImagickDraw::setClipPath example
  • Example#3033 - ImagickDraw::setClipRule example
  • Example#3034 - ImagickDraw::setClipUnits example
  • Example#3035 - ImagickDraw::setFillAlpha example
  • Example#3036 - ImagickDraw::setFillColor
  • Example#3037 - ImagickDraw::setFillOpacity
  • Example#3038 - ImagickDraw::setFillRule example
  • Example#3039 - ImagickDraw::setFont example
  • Example#3040 - ImagickDraw::setFontFamily example
  • Example#3041 - ImagickDraw::setFontSize example
  • Example#3042 - ImagickDraw::setFontStretch example
  • Example#3043 - ImagickDraw::setFontStyle example
  • Example#3044 - ImagickDraw::setFontWeight example
  • Example#3045 - ImagickDraw::setGravity example
  • Example#3046 - ImagickDraw::setStrokeAlpha example
  • Example#3047 - ImagickDraw::setStrokeAntialias example
  • Example#3048 - ImagickDraw::setStrokeColor example
  • Example#3049 - ImagickDraw::setStrokeDashArray example
  • Example#3050 - ImagickDraw::setStrokeDashOffset example
  • Example#3051 - ImagickDraw::setStrokeLineCap example
  • Example#3052 - ImagickDraw::setStrokeLineJoin example
  • Example#3053 - ImagickDraw::setStrokeMiterLimit example
  • Example#3054 - ImagickDraw::setStrokeOpacity example
  • Example#3055 - ImagickDraw::setStrokeWidth example
  • Example#3056 - ImagickDraw::setTextAlignment example
  • Example#3057 - ImagickDraw::setTextAntialias example
  • Example#3058 - ImagickDraw::setTextDecoration example
  • Example#3059 - ImagickDraw::setTextUnderColor example
  • Example#3060 - ImagickDraw::setVectorGraphics example
  • Example#3061 - ImagickDraw::setViewBox example
  • Example#3062 - ImagickDraw::skewX example
  • Example#3063 - ImagickDraw::skewY example
  • Example#3064 - ImagickDraw::translate example
  • Example#3065 - ImagickPixel::construct
  • Example#3066 - Basic Imagick::getColor usage
  • Example#3067 - Basic Imagick::getColorAsString usage
  • Example#3068 - ImagickPixel getColorCount
  • Example#3069 - Basic Imagick::getColorValue usage
  • Example#3070 - ImagickPixel::getColorValueQuantum
  • Example#3071 - Basic Imagick::getHSL example
  • Example#3072 - ImagickPixel::isSimilar
  • Example#3073 - ImagickPixel::setColor
  • Example#3074 - Basic Imagick::setColorValue usage
  • Example#3075 - ImagickPixel::setColorValueQuantum
  • Example#3076 - Use ImagickPixel::setHSL to modify a color
  • Example#3077 - ImagickPixelIterator::clear
  • Example#3078 - ImagickPixelIterator::construct
  • Example#3079 - ImagickPixelIterator::getNextIteratorRow
  • Example#3080 - ImagickPixelIterator::resetIterator
  • Example#3081 - ImagickPixelIterator::setIteratorRow
  • Example#3082 - ImagickKernel::addKernel
  • Example#3083 - ImagickKernel::addUnityKernel
  • Example#3084 - ImagickKernel::addUnityKernel
  • Example#3085 - ImagickKernel::fromBuiltin
  • Example#3086 - ImagickKernel::fromMatrix
  • Example#3087 - ImagickKernel::getMatrix
  • Example#3088 - ImagickKernel::scale
  • Example#3089 - ImagickKernel::separate
  • Example#3090 - imap_append example
  • Example#3091 - imap_check example
  • Example#3092 - imap_createmailbox example
  • Example#3093 - imap_delete example
  • Example#3094 - imap_fetch_overview example
  • Example#3095 - imap_gc example
  • Example#3096 - imap_get_quota example
  • Example#3097 - imap_get_quota 4.3 or greater example
  • Example#3098 - imap_get_quotaroot example
  • Example#3099 - imap_getacl example
  • Example#3100 - imap_getmailboxes example
  • Example#3101 - imap_is_open example
  • Example#3102 - imap_list example
  • Example#3103 - imap_mail_compose example
  • Example#3104 - imap_mailboxmsginfo example
  • Example#3105 - imap_mime_header_decode example
  • Example#3106 - Different use of imap_open
  • Example#3107 - imap_open example
  • Example#3108 - imap_ping Example
  • Example#3109 - imap_reopen example
  • Example#3110 - imap_rfc822_parse_adrlist example
  • Example#3111 - imap_rfc822_write_address example
  • Example#3112 - imap_search example
  • Example#3113 - imap_set_quota example
  • Example#3114 - imap_setflag_full example
  • Example#3115 - imap_status example
  • Example#3116 - imap_thread Example
  • Example#3117 - imap_timeout example
  • Example#3118 - Basic imap_utf8 Usage
  • Example#3119 - Calculating the hash and subscribing a user
  • Example#3120 - Sending mail.
  • Example#3121 - Sending mail with extra headers.
  • Example#3122 - Sending mail with extra headers as array
  • Example#3123 - Sending mail with an additional command line parameter.
  • Example#3124 - Sending HTML email
  • Example#3125 - mailparse_determine_best_xfer_encoding example
  • Example#3126 - mailparse_rfc822_parse_addresses example
  • Example#3127 - mailparse_stream_encode example
  • Example#3128 - mailparse_uudecode_all example
  • Example#3129 - bcadd example
  • Example#3130 - bccomp example
  • Example#3131 - bcdiv example
  • Example#3132 - bcmod example
  • Example#3133 - bcmod with decimals
  • Example#3134 - bcmul example
  • Example#3135 - bcmul scale example
  • Example#3136 - bcpow example
  • Example#3137 - bcpow scale example
  • Example#3138 - bcscale example
  • Example#3139 - bcsqrt example
  • Example#3140 - bcsub example
  • Example#3141 - Factorial function using GMP
  • Example#3142 - gmp_abs example
  • Example#3143 - gmp_add example
  • Example#3144 - gmp_and example
  • Example#3145 - gmp_clrbit example
  • Example#3146 - gmp_cmp example
  • Example#3147 - gmp_com example
  • Example#3148 - gmp_div_q example
  • Example#3149 - Division of GMP numbers
  • Example#3150 - gmp_div_r example
  • Example#3151 - gmp_divexact example
  • Example#3152 - gmp_export example
  • Example#3153 - gmp_fact example
  • Example#3154 - gmp_gcd example
  • Example#3155 - Solving a linear Diophantine equation
  • Example#3156 - gmp_hamdist example
  • Example#3157 - gmp_import example
  • Example#3158 - Creating GMP number
  • Example#3159 - gmp_intval example
  • Example#3160 - gmp_invert example
  • Example#3161 - gmp_jacobi example
  • Example#3162 - gmp_legendre example
  • Example#3163 - gmp_mod example
  • Example#3164 - gmp_mul example
  • Example#3165 - gmp_neg example
  • Example#3166 - gmp_nextprime example
  • Example#3167 - gmp_or example
  • Example#3168 - gmp_perfect_square example
  • Example#3169 - gmp_popcount example
  • Example#3170 - gmp_pow example
  • Example#3171 - gmp_powm example
  • Example#3172 - gmp_prob_prime example
  • Example#3173 - gmp_random_bits example
  • Example#3174 - gmp_random_range example
  • Example#3175 - gmp_random_seed example
  • Example#3176 - gmp_random example
  • Example#3177 - gmp_scan0 example
  • Example#3178 - gmp_scan1 example
  • Example#3179 - gmp_setbit example - 0 index
  • Example#3180 - gmp_setbit example - 1 index
  • Example#3181 - gmp_setbit example - clearing a bit
  • Example#3182 - gmp_sign example
  • Example#3183 - gmp_sqrt example
  • Example#3184 - gmp_sqrtrem example
  • Example#3185 - Converting a GMP number to a string
  • Example#3186 - gmp_sub example
  • Example#3187 - gmp_testbit example
  • Example#3188 - gmp_xor example
  • Example#3189 - abs example
  • Example#3190 - base_convert example
  • Example#3191 - bindec example
  • Example#3192 - bindec interprets input as unsigned integers
  • Example#3193 - ceil example
  • Example#3194 - cos example
  • Example#3195 - decbin example
  • Example#3196 - dechex example
  • Example#3197 - dechex example with large integers
  • Example#3198 - decoct example
  • Example#3199 - deg2rad example
  • Example#3200 - exp example
  • Example#3201 - Using fdiv
  • Example#3202 - floor example
  • Example#3203 - Using fmod
  • Example#3204 - hexdec example
  • Example#3205 - intdiv example
  • Example#3206 - is_finite example
  • Example#3207 - is_infinite example
  • Example#3208 - is_nan example
  • Example#3209 - Example uses of max
  • Example#3210 - Example uses of min
  • Example#3211 - octdec example
  • Example#3212 - pi example
  • Example#3213 - Some examples of pow
  • Example#3214 - rad2deg example
  • Example#3215 - round examples
  • Example#3216 - How precision affects a float
  • Example#3217 - mode examples
  • Example#3218 - mode with precision examples
  • Example#3219 - sin example
  • Example#3220 - sqrt example
  • Example#3221 - tan example
  • Example#3222 - Evaluating a FDF document
  • Example#3223 - Adding JavaScript code to a FDF
  • Example#3224 - Populating a PDF document
  • Example#3225 - Storing an uploaded file
  • Example#3226 - Detecting all fieldnames in a FDF
  • Example#3227 - Accessing the form data
  • Example#3228 - Accessing the form data
  • Example#3229 - Retrieving FDF as a string
  • Example#3230 - Passing FDF data to a second form
  • Example#3231 - gnupg clearsign example (procedural)
  • Example#3232 - gnupg clearsign example (OO)
  • Example#3233 - keylistiterator
  • Example#3234 - Procedural gnupg_adddecryptkey example
  • Example#3235 - OO gnupg_adddecryptkey example
  • Example#3236 - Procedural gnupg_addencryptkey example
  • Example#3237 - OO gnupg_addencryptkey example
  • Example#3238 - Procedural gnupg_addsignkey example
  • Example#3239 - OO gnupg_addsignkey example
  • Example#3240 - Procedural gnupg_cleardecryptkeys example
  • Example#3241 - OO gnupg_cleardecryptkeys example
  • Example#3242 - Procedural gnupg_clearencryptkeys example
  • Example#3243 - OO gnupg_clearencryptkeys example
  • Example#3244 - Procedural gnupg_clearsignkeys example
  • Example#3245 - OO gnupg_clearsignkeys example
  • Example#3246 - Procedural gnupg_decrypt example
  • Example#3247 - OO gnupg_decrypt example
  • Example#3248 - Procedural gnupg_decryptverify example
  • Example#3249 - OO gnupg_decryptverify example
  • Example#3250 - Procedural gnupg_deletekey example
  • Example#3251 - OO gnupg_deletekey example
  • Example#3252 - Procedural gnupg_encrypt example
  • Example#3253 - OO gnupg_encrypt example
  • Example#3254 - Procedural gnupg_encryptsign example
  • Example#3255 - OO gnupg_encryptsign example
  • Example#3256 - Procedural gnupg_export example
  • Example#3257 - OO gnupg_export example
  • Example#3258 - Procedural gnupg_getengineinfo example
  • Example#3259 - OO gnupg_getengineinfo example
  • Example#3260 - Procedural gnupg_geterror example
  • Example#3261 - OO gnupg_geterror example
  • Example#3262 - Procedural gnupg_geterrorinfo example
  • Example#3263 - OO gnupg_geterrorinfo example
  • Example#3264 - Procedural gnupg_getprotocol example
  • Example#3265 - OO gnupg_getprotocol example
  • Example#3266 - Procedural gnupg_gettrustlist example
  • Example#3267 - OO gnupg_gettrustlist example
  • Example#3268 - Procedural gnupg_import example
  • Example#3269 - OO gnupg_import example
  • Example#3270 - Procedural gnupg_init example with default setting
  • Example#3271 - Procedural gnupg_init example with overriden file name and home dir
  • Example#3272 - OO gnupg initializer example with default setting
  • Example#3273 - OO gnupg initializer example with overriden file name and home dir
  • Example#3274 - Procedural gnupg_keyinfo example
  • Example#3275 - OO gnupg_keyinfo example
  • Example#3276 - Procedural gnupg_listsignatures example
  • Example#3277 - OO gnupg_listsignatures example
  • Example#3278 - Procedural gnupg_setarmor example
  • Example#3279 - OO gnupg_setarmor example
  • Example#3280 - Procedural gnupg_seterrormode example
  • Example#3281 - OO gnupg_seterrormode example
  • Example#3282 - Procedural gnupg_setsignmode example
  • Example#3283 - OO gnupg_setsignmode example
  • Example#3284 - Procedural gnupg_sign example
  • Example#3285 - OO gnupg_sign example
  • Example#3286 - Procedural gnupg_verify example
  • Example#3287 - OO gnupg_verify example
  • Example#3288 - Creating and using a pattern
  • Example#3289 - Creating and using a template
  • Example#3290 - Hyphennate a text
  • Example#3291 - Drawing a rectangle
  • Example#3292 - Creating and using a spot color
  • Example#3293 - Rotation of the coordinate system
  • Example#3294 - Placing text at a given position
  • Example#3295 - Drawing a dashed line
  • Example#3296 - Translation of the coordinate system
  • Example#3297 - A rpmdbinfo example
  • Example#3298 - Searching for the package owning a file
  • Example#3299 - A rpminfo example
  • Example#3300 - example
  • Example#3301 - example
  • Example#3302 - example
  • Example#3303 - example
  • Example#3304 - example
  • Example#3305 - example
  • Example#3306 - example
  • Example#3307 - example
  • Example#3308 - example
  • Example#3309 - example
  • Example#3310 - example
  • Example#3311 - example
  • Example#3312 - example
  • Example#3313 - example
  • Example#3314 - example
  • Example#3315 - example
  • Example#3316 - example
  • Example#3317 - example
  • Example#3318 - example
  • Example#3319 - Incorrect requests
  • Example#3320 - Calling request from a request callback
  • Example#3321 - Calling request from a request callback
  • Example#3322 - Using eio with libevent
  • Example#3323 - Cancelling a request
  • Example#3324 - Calling eio_chmod
  • Example#3325 - Making a custom request
  • Example#3326 - Grouping requests
  • Example#3327 - Using eio with libevent extension
  • Example#3328 - Using eio with event extension
  • Example#3329 - eio_cancel example
  • Example#3330 - eio_custom example
  • Example#3331 - eio_event_loop example
  • Example#3332 - eio_lstat example
  • Example#3333 - Using eio with libevent
  • Example#3334 - Grouping requests
  • Example#3335 - eio_grp example
  • Example#3336 - eio_link example
  • Example#3337 - eio_lstat example
  • Example#3338 - eio_mkdir example
  • Example#3339 - eio_mknod example
  • Example#3340 - eio_nreqs example
  • Example#3341 - eio_open example
  • Example#3342 - eio_poll example
  • Example#3343 - eio_read example
  • Example#3344 - eio_readdir example
  • Example#3345 - eio_readlink example
  • Example#3346 - eio_realpath example
  • Example#3347 - eio_rename example
  • Example#3348 - eio_rmdir example
  • Example#3349 - eio_stat example
  • Example#3350 - eio_statvfs example
  • Example#3351 - eio_symlink example
  • Example#3352 - Simple timers
  • Example#3353 - Periodic timer. Tick each 10.5 seconds
  • Example#3354 - Periodic timer. Use reschedule callback
  • Example#3355 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3356 - Wait until STDIN is readable
  • Example#3357 - Use some async I/O to access a socket
  • Example#3358 - Embedding one loop into another
  • Example#3359 - Embedding loop created with kqueue backend into the default loop
  • Example#3360 - Handle SIGTERM signal
  • Example#3361 - Monitor changes of /var/log/messages
  • Example#3362 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3363 - Process status changes
  • Example#3364 - Using reschedule callback
  • Example#3365 - Embedding loop created with kqueue backend into the default loop
  • Example#3366 - Embedding one loop into another
  • Example#3367 - Embedding loop created with kqueue backend into the default loop
  • Example#3368 - Embedding loop created with kqueue backend into the default loop
  • Example#3369 - Periodic timer. Use reschedule callback
  • Example#3370 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3371 - Hourly watcher
  • Example#3372 - Handle SIGTERM signal
  • Example#3373 - Monitor changes of /var/log/messages
  • Example#3374 - Monitor changes of /var/log/messages
  • Example#3375 - Simple timers
  • Example#3376 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3377 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3378 - Expect Usage Example
  • Example#3379 - Another Expect Usage Example
  • Example#3380 - expect_expectl example
  • Example#3381 - expect_popen example
  • Example#3382 - Process Control Example
  • Example#3383 - pcntl_fork example
  • Example#3384 - pcntl_rfork example
  • Example#3385 - pcntl_signal_dispatch example
  • Example#3386 - pcntl_signal_get_handler example
  • Example#3387 - pcntl_signal example
  • Example#3388 - pcntl_sigprocmask example
  • Example#3389 - pcntl_sigwaitinfo example
  • Example#3390 - posix_access example
  • Example#3391 - posix_ctermid example
  • Example#3392 - posix_eaccess example
  • Example#3393 - posix_fpathconf example
  • Example#3394 - posix_get_last_error example
  • Example#3395 - posix_getcwd example
  • Example#3396 - posix_getegid example
  • Example#3397 - posix_geteuid example
  • Example#3398 - posix_getgid example
  • Example#3399 - Example use of posix_getgrgid
  • Example#3400 - Example use of posix_getgrnam
  • Example#3401 - Example use of posix_getgroups
  • Example#3402 - Example use of posix_getlogin
  • Example#3403 - Example use of posix_getpgid
  • Example#3404 - Example use of posix_getpid
  • Example#3405 - Example use of posix_getppid
  • Example#3406 - Example use of posix_getpwnam
  • Example#3407 - Example use of posix_getpwuid
  • Example#3408 - Example use of posix_getrlimit
  • Example#3409 - Example use of posix_getsid
  • Example#3410 - Example use of posix_getuid
  • Example#3411 - A posix_mknod example
  • Example#3412 - posix_pathconf example
  • Example#3413 - posix_setegid example
  • Example#3414 - posix_setgid example
  • Example#3415 - posix_setuid example
  • Example#3416 - posix_strerror example
  • Example#3417 - posix_sysconf example
  • Example#3418 - Example use of posix_times
  • Example#3419 - Example use of posix_uname
  • Example#3420 - escapeshellarg example
  • Example#3421 - escapeshellcmd example
  • Example#3422 - An exec example
  • Example#3423 - Using proc_nice to set the process priority to high
  • Example#3424 - A proc_open example
  • Example#3425 - proc_open quirk on Windows
  • Example#3426 - A shell_exec example
  • Example#3427 - system example
  • Example#3428 - Example showing Future as return value
  • Example#3429 - Example showing Future as synchronization point
  • Example#3430 - Fetch a chunk of the property table
  • Example#3431 - Counting the properties of an object
  • Example#3432 - Runtime inheritance
  • Example#3433 - Detect the state of the referenced object
  • Example#3434 - Detect the state of the referenced object
  • Example#3435 - Merging into the property table of a threaded object
  • Example#3436 - Notifications and Waiting
  • Example#3437 - Notifications and Waiting
  • Example#3438 - Popping the last item from the property table of a threaded object
  • Example#3439 - Shifting the first item from the property table of a threaded object
  • Example#3440 - Synchronizing
  • Example#3441 - Notifications and Waiting
  • Example#3442 - Return the identity of the Thread or Process that created the referenced Thread
  • Example#3443 - Return the currently executing Thread
  • Example#3444 - Return the identity of the currently executing Thread
  • Example#3445 - Return the identity of the referenced Thread
  • Example#3446 - Detect the state of the referenced Thread
  • Example#3447 - Tell if the referenced Thread was started
  • Example#3448 - Join with the referenced Thread
  • Example#3449 - Starting Threads
  • Example#3450 - A basic example of Worker::collect
  • Example#3451 - A basic example of Worker::getStacked
  • Example#3452 - Detect the state of a worker
  • Example#3453 - Shutdown the referenced worker
  • Example#3454 - Stacking a task for execution onto a worker
  • Example#3455 - Removing objects from the stack of Workers
  • Example#3456 - A basic example of Pool::collect
  • Example#3457 - Creating Pools
  • Example#3458 - Shutting down a pool
  • Example#3459 - Submitting Tasks
  • Example#3460 - Submitting tasks to a specific worker
  • Example#3461 - New immutability semantics of Threaded
  • Example#3462 - Volatile use-case
  • Example#3463 - Shared Memory Operations Overview
  • Example#3464 - Closing shared memory block
  • Example#3465 - Deleting shared memory block
  • Example#3466 - Create a new shared memory block
  • Example#3467 - Reading shared memory block
  • Example#3468 - Getting the size of the shared memory block
  • Example#3469 - Writing to shared memory block
  • Example#3470 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3471 - SyncMutex::__construct unnamed mutex example
  • Example#3472 - SyncMutex::lock example
  • Example#3473 - SyncMutex::unlock example
  • Example#3474 - SyncSemaphore::__construct example
  • Example#3475 - SyncSemaphore::lock example
  • Example#3476 - SyncSemaphore::unlock example
  • Example#3477 - SyncEvent::__construct example
  • Example#3478 - SyncEvent::fire example
  • Example#3479 - SyncEvent::reset example
  • Example#3480 - SyncEvent::wait example
  • Example#3481 - SyncReaderWriter::__construct example
  • Example#3482 - SyncReaderWriter::readlock example
  • Example#3483 - SyncReaderWriter::readunlock example
  • Example#3484 - SyncReaderWriter::writelock example
  • Example#3485 - SyncReaderWriter::writeunlock example
  • Example#3486 - SyncSharedMemory::__construct example
  • Example#3487 - SyncSharedMemory::first example
  • Example#3488 - SyncSharedMemory::__construct example
  • Example#3489 - SyncSharedMemory::size example
  • Example#3490 - SyncSharedMemory::write example
  • Example#3491 - A geoip_asnum_by_name example
  • Example#3492 - A geoip_continent_code_by_name example
  • Example#3493 - A geoip_country_code_by_name example
  • Example#3494 - A geoip_country_code3_by_name example
  • Example#3495 - A geoip_country_name_by_name example
  • Example#3496 - A geoip_database_info example
  • Example#3497 - A geoip_db_avail example
  • Example#3498 - A geoip_db_filename example
  • Example#3499 - A geoip_db_get_all_info example
  • Example#3500 - A geoip_db_get_all_info example
  • Example#3501 - A geoip_domain_by_name example
  • Example#3502 - A geoip_id_by_name example
  • Example#3503 - A geoip_isp_by_name example
  • Example#3504 - A geoip_netspeedcell_by_name example
  • Example#3505 - A geoip_org_by_name example
  • Example#3506 - A geoip_record_by_name example
  • Example#3507 - A geoip_region_by_name example
  • Example#3508 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#3509 - A geoip_region_name_by_code example using FIPS codes
  • Example#3510 - A geoip_setup_custom_directory example
  • Example#3511 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#3512 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#3513 - xor.data file
  • Example#3514 - Simple train
  • Example#3515 - Simple test
  • Example#3516 - fann_create_train_from_callback example
  • Example#3517 - fann_read_train_from_file example
  • Example#3518 - igbinary_serialize example
  • Example#3519 - JsonSerializable::jsonSerialize example returning an array
  • Example#3520 - JsonSerializable::jsonSerialize example returning an associative array
  • Example#3521 - JsonSerializable::jsonSerialize example returning an int
  • Example#3522 - JsonSerializable::jsonSerialize example returning a string
  • Example#3523 - json_decode examples
  • Example#3524 - Accessing invalid object properties
  • Example#3525 - common mistakes using json_decode
  • Example#3526 - depth errors
  • Example#3527 - json_decode of large integers
  • Example#3528 - A json_encode example
  • Example#3529 - A json_encode example showing some flags in use
  • Example#3530 - JSON_NUMERIC_CHECK option example
  • Example#3531 - Sequential versus non-sequential array example
  • Example#3532 - JSON_PRESERVE_ZERO_FRACTION option example
  • Example#3533 - json_last_error example
  • Example#3534 - json_last_error with json_encode
  • Example#3535 - json_last_error and JSON_THROW_ON_ERROR
  • Example#3536 - json_validate examples
  • Example#3537 - simdjson_decode examples
  • Example#3538 - Accessing invalid object properties
  • Example#3539 - common mistakes using simdjson_decode
  • Example#3540 - depth errors
  • Example#3541 - simdjson_decode of large integers
  • Example#3542 - simdjson_decode examples
  • Example#3543 - depth errors
  • Example#3544 - Lua::assignexample
  • Example#3545 - Lua::callexample
  • Example#3546 - Lua::evalexample
  • Example#3547 - Lua::registerCallbackexample
  • Example#3548 - LuaClosure::__invokeexample
  • Example#3549 - Execute some Lua code
  • Example#3550 - Calling a Lua function
  • Example#3551 - Profiling Lua code
  • Example#3552 - Loading code into Lua
  • Example#3553 - Manipulating the usage timer
  • Example#3554 - Registering PHP functions to call from Lua
  • Example#3555 - Calling a Lua function
  • Example#3556 - Calling a Lua function
  • Example#3557 - Using constant with Constants
  • Example#3558 - Using constant with Enum Cases (as of PHP 8.1.0)
  • Example#3559 - Defining Constants
  • Example#3560 - Constants with Reserved Names
  • Example#3561 - Checking Constants
  • Example#3562 - Checking Enum Cases (as of PHP 8.1.0)
  • Example#3563 - eval example - simple text merge
  • Example#3564 - exit example
  • Example#3565 - exit status example
  • Example#3566 - Shutdown functions and destructors run regardless
  • Example#3567 - Listing all information about the users browser
  • Example#3568 - A __halt_compiler example
  • Example#3569 - highlight_string example
  • Example#3570 - hrtime usage
  • Example#3571 - A ignore_user_abort example
  • Example#3572 - pack example
  • Example#3573 - php_strip_whitespace example
  • Example#3574 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3575 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3576 - sapi_windows_vt100_support default state
  • Example#3577 - sapi_windows_vt100_support changing state
  • Example#3578 - Example usage of VT100 support enabled
  • Example#3579 - sleep example
  • Example#3580 - A sys_getloadavg example
  • Example#3581 - time_nanosleep example
  • Example#3582 - A time_sleep_until example
  • Example#3583 - uniqid Example
  • Example#3584 - unpack example
  • Example#3585 - unpack example with a repeater
  • Example#3586 - unpack example with unnamed keys
  • Example#3587 - usleep example
  • Example#3588 - Random Example
  • Example#3589 - mt_rand example
  • Example#3590 - rand example
  • Example#3591 - random_bytes example
  • Example#3592 - random_int example
  • Example#3593 - Random\Randomizer::__construct example
  • Example#3594 - Random\Randomizer::getBytes example
  • Example#3595 - Random\Randomizer::getBytesFromString example
  • Example#3596 - Generate a random code for multi-factor authentication
  • Example#3597 - Select from a string with a non-uniform distribution
  • Example#3598 - Random\Randomizer::getFloat example
  • Example#3599 - Random\Randomizer::getInt example
  • Example#3600 - Random\Randomizer::nextFloat example
  • Example#3601 - Incorrect scaling using an affine transformation
  • Example#3602 - Random\Randomizer::nextInt example
  • Example#3603 - Random\Randomizer::pickArrayKeys example
  • Example#3604 - Picking random values
  • Example#3605 - Random\Randomizer::__serialize example
  • Example#3606 - Random\Randomizer::shuffleArray example
  • Example#3607 - Random\Randomizer::shuffleBytes example
  • Example#3608 - Byte-wise shuffling breaks Unicode characters
  • Example#3609 - Random\Randomizer::__unserialize example
  • Example#3610 - Random\Engine::generate example
  • Example#3611 - Random\Engine\Mt19937::__construct example
  • Example#3612 - Random\Engine\Mt19937::__debugInfo example
  • Example#3613 - Random\Engine\Mt19937::__serialize example
  • Example#3614 - Random\Engine\Mt19937::__unserialize example
  • Example#3615 - Random\Engine\PcgOneseq128XslRr64::__construct example
  • Example#3616 - Deriving a seed from a string
  • Example#3617 - Random\Engine\PcgOneseq128XslRr64::__debugInfo example
  • Example#3618 - Random\Engine\PcgOneseq128XslRr64::jump example
  • Example#3619 - Randomizer methods may call the engine more than once
  • Example#3620 - Random\Engine\PcgOneseq128XslRr64::__serialize example
  • Example#3621 - Random\Engine\PcgOneseq128XslRr64::__unserialize example
  • Example#3622 - Random\Engine\Xoshiro256StarStar::__construct example
  • Example#3623 - Deriving a seed from a string
  • Example#3624 - Random\Engine\Xoshiro256StarStar::__debugInfo example
  • Example#3625 - Random\Engine\Xoshiro256StarStar::jump example
  • Example#3626 - Random\Engine\Xoshiro256StarStar::jumpLong example
  • Example#3627 - Random\Engine\Xoshiro256StarStar::__serialize example
  • Example#3628 - Random\Engine\Xoshiro256StarStar::__unserialize example
  • Example#3629 - Get and set base path
  • Example#3630 - Get and set logger
  • Example#3631 - Fast write log
  • Example#3632 - Fast count some type of log count value
  • Example#3633 - Acquisit some type of log list
  • Example#3634 - seaslog_get_author example
  • Example#3635 - seaslog_get_version example
  • Example#3636 - SeasLog::alert example
  • Example#3637 - SeasLog::analyzerCount example
  • Example#3638 - SeasLog::analyzerDetail example
  • Example#3639 - SeasLog::closeLoggerStream example
  • Example#3640 - SeasLog::__construct example
  • Example#3641 - SeasLog::critical example
  • Example#3642 - SeasLog::debug example
  • Example#3643 - SeasLog::__destruct example
  • Example#3644 - SeasLog::emergency example
  • Example#3645 - SeasLog::error example
  • Example#3646 - SeasLog::flushBuffer example
  • Example#3647 - SeasLog::getBasePath example
  • Example#3648 - SeasLog::getBuffer example
  • Example#3649 - SeasLog::getBufferEnabled example
  • Example#3650 - SeasLog::getDatetimeFormat example
  • Example#3651 - SeasLog::getLastLogger example
  • Example#3652 - SeasLog::getRequestID example
  • Example#3653 - SeasLog::getRequestVariable example
  • Example#3654 - SeasLog::info example
  • Example#3655 - SeasLog::log example
  • Example#3656 - SeasLog::notice example
  • Example#3657 - SeasLog::setBasePath example
  • Example#3658 - SeasLog::setDatetimeFormat example
  • Example#3659 - SeasLog::setLogger example
  • Example#3660 - SeasLog::setRequestID example
  • Example#3661 - SeasLog::setRequestVariable example
  • Example#3662 - SeasLog::warning example
  • Example#3663 - SplStack example
  • Example#3664 - SplQueue example
  • Example#3665 - Efficiently handling tasks with SplQueue
  • Example#3666 - SplFixedArray usage example
  • Example#3667 - SplFixedArray::__construct example
  • Example#3668 - SplFixedArray::count example
  • Example#3669 - SplFixedArray::fromArray example
  • Example#3670 - SplFixedArray::getSize example
  • Example#3671 - SplFixedArray::setSize example
  • Example#3672 - SplFixedArray::toArray example
  • Example#3673 - SplObjectStorage as a set
  • Example#3674 - SplObjectStorage as a map
  • Example#3675 - SplObjectStorage::addAll example
  • Example#3676 - SplObjectStorage::attach example
  • Example#3677 - SplObjectStorage::contains example
  • Example#3678 - SplObjectStorage::count example
  • Example#3679 - SplObjectStorage::current example
  • Example#3680 - SplObjectStorage::detach example
  • Example#3681 - SplObjectStorage::getHash example
  • Example#3682 - SplObjectStorage::getInfo example
  • Example#3683 - SplObjectStorage::key example
  • Example#3684 - SplObjectStorage::next example
  • Example#3685 - SplObjectStorage::offsetExists example
  • Example#3686 - SplObjectStorage::offsetGet example
  • Example#3687 - SplObjectStorage::offsetSet example
  • Example#3688 - SplObjectStorage::offsetUnset example
  • Example#3689 - SplObjectStorage::removeAll example
  • Example#3690 - SplObjectStorage::removeAllExcept example
  • Example#3691 - SplObjectStorage::rewind example
  • Example#3692 - SplObjectStorage::serialize example
  • Example#3693 - SplObjectStorage::setInfo example
  • Example#3694 - SplObjectStorage::unserialize example
  • Example#3695 - SplObjectStorage::valid example
  • Example#3696 - AppendIterator::append example
  • Example#3697 - Iterating AppendIterator with foreach
  • Example#3698 - Iterating AppendIterator with the AppendIterator API
  • Example#3699 - AppendIterator.getIteratorIndex basic example
  • Example#3700 - AppendIterator::key basic example
  • Example#3701 - ArrayIterator::current example
  • Example#3702 - ArrayIterator::key example
  • Example#3703 - ArrayIterator::next example
  • Example#3704 - ArrayIterator::rewind example
  • Example#3705 - ArrayIterator::valid example
  • Example#3706 - CachingIterator::getCache example
  • Example#3707 - Available callback arguments
  • Example#3708 - Callback basic examples
  • Example#3709 - A DirectoryIterator::__construct example
  • Example#3710 - A DirectoryIterator::current example
  • Example#3711 - A DirectoryIterator::getBasename example
  • Example#3712 - DirectoryIterator::getExtension example
  • Example#3713 -
  • Example#3714 - A DirectoryIterator::getFilename example
  • Example#3715 - A DirectoryIterator::isDot example
  • Example#3716 - A DirectoryIterator::key example
  • Example#3717 - DirectoryIterator::next example
  • Example#3718 - DirectoryIterator::rewind example
  • Example#3719 - DirectoryIterator::seek example
  • Example#3720 - A DirectoryIterator::__toString example
  • Example#3721 - A DirectoryIterator::valid example
  • Example#3722 - FilesystemIterator::__construct example
  • Example#3723 - FilesystemIterator::current example
  • Example#3724 - FilesystemIterator::key example
  • Example#3725 - FilesystemIterator::next example
  • Example#3726 - FilesystemIterator::rewind example
  • Example#3727 - FilesystemIterator::key example
  • Example#3728 - FilterIterator::accept example
  • Example#3729 - GlobIterator example
  • Example#3730 - GlobIterator::count example
  • Example#3731 - InfiniteIterator::__construct example
  • Example#3732 - LimitIterator usage example
  • Example#3733 - LimitIterator::__construct example
  • Example#3734 - LimitIterator::getPosition example
  • Example#3735 - Iterating a MultipleIterator
  • Example#3736 - NoRewindIterator::__construct example
  • Example#3737 - NoRewindIterator::rewind example
  • Example#3738 - RecursiveArrayIterator::getChildren example
  • Example#3739 - RecursiveArrayIterator::hasChildren example
  • Example#3740 - Available callback arguments
  • Example#3741 - Recursive callback basic example
  • Example#3742 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#3743 - RecursiveDirectoryIterator example
  • Example#3744 - getSubPath example
  • Example#3745 - getSubPathname example
  • Example#3746 - Basic RecursiveFilterIterator example
  • Example#3747 - RecursiveFilterIterator example
  • Example#3748 - Iterating a RecursiveIteratorIterator
  • Example#3749 - RecursiveRegexIterator::__construct example
  • Example#3750 - RecursiveRegexIterator::getChildren example
  • Example#3751 - RecursiveRegexIterator::hasChildren example
  • Example#3752 - RegexIterator::accept example
  • Example#3753 - RegexIterator::__construct example
  • Example#3754 - RegexIterator::getFlags example
  • Example#3755 - RegexIterator::getMode example
  • Example#3756 - RegexIterator::getPregFlags example
  • Example#3757 - RegexIterator::setFlags example
  • Example#3758 - RegexIterator::setMode example
  • Example#3759 - RegexIterator::setPregFlags example
  • Example#3760 - Countable::count example
  • Example#3761 - Basic usage
  • Example#3762 - SeekableIterator::seek example
  • Example#3763 - class_implements example
  • Example#3764 - class_parents example
  • Example#3765 - class_uses example
  • Example#3766 - iterator_apply example
  • Example#3767 - iterator_count example
  • Example#3768 - iterator_count modifies position
  • Example#3769 - iterator_count in foreach loops
  • Example#3770 - iterator_to_array example
  • Example#3771 - spl_autoload_extensions example
  • Example#3772 - spl_autoload_register as a replacement for an __autoload function
  • Example#3773 - spl_autoload_register example where the class is not loaded
  • Example#3774 - The identifier will be provided without the leading backslash
  • Example#3775 - spl_classes example
  • Example#3776 - A spl_object_hash example
  • Example#3777 - A spl_object_id example
  • Example#3778 - SplFileInfo::__construct example
  • Example#3779 - SplFileInfo::getATime example
  • Example#3780 - SplFileInfo::getBasename example
  • Example#3781 - SplFileInfo::getCTime example
  • Example#3782 - SplFileInfo::getExtension example
  • Example#3783 -
  • Example#3784 - SplFileInfo::getFilename example
  • Example#3785 - SplFileInfo::getGroup example
  • Example#3786 - SplFileInfo::getLinkTarget example
  • Example#3787 - SplFileInfo::getMTime example
  • Example#3788 - SplFileInfo::getOwner example
  • Example#3789 - SplFileInfo::getPath example
  • Example#3790 - SplFileInfo::getPathInfo example
  • Example#3791 - SplFileInfo::getPathname example
  • Example#3792 - SplFileInfo::getPerms example
  • Example#3793 - SplFileInfo::getRealPath example
  • Example#3794 - SplFileInfo::getSize example
  • Example#3795 - SplFileInfo::getType example
  • Example#3796 - SplFileInfo::isDir example
  • Example#3797 - SplFileInfo::isExecutable example
  • Example#3798 - SplFileInfo::isFile example
  • Example#3799 - SplFileInfo::isLink example
  • Example#3800 - SplFileInfo::isReadable example
  • Example#3801 - SplFileInfo::isWriteable example
  • Example#3802 - SplFileInfo::openFile example
  • Example#3803 - SplFileInfo::setFileClass example
  • Example#3804 - SplFileInfo::setFileClass example
  • Example#3805 - SplFileInfo::__toString example
  • Example#3806 - SplFileObject::__construct example
  • Example#3807 - SplFileObject::current example
  • Example#3808 - SplFileObject::eof example
  • Example#3809 - SplFileObject::fflush example
  • Example#3810 - SplFileObject::fgetc example
  • Example#3811 - SplFileObject::fgetcsv example
  • Example#3812 - SplFileObject::READ_CSV example
  • Example#3813 - SplFileObject::fgets example
  • Example#3814 - SplFileObject::fgetss example
  • Example#3815 - SplFileObject::flock example
  • Example#3816 - SplFileObject::fpassthru example
  • Example#3817 - SplFileObject::fputcsv example
  • Example#3818 - SplFileObject::fread example
  • Example#3819 - SplFileObject::fscanf example
  • Example#3820 - SplFileObject::fseek example
  • Example#3821 - SplFileObject::fstat example
  • Example#3822 - SplFileObject::ftell example
  • Example#3823 - SplFileObject::ftruncate example
  • Example#3824 - SplFileObject::fwrite example
  • Example#3825 - SplFileObject::getCsvControl example
  • Example#3826 - SplFileObject::getFlags example
  • Example#3827 - SplFileObject::getMaxLineLen example
  • Example#3828 - SplFileObject::key example
  • Example#3829 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#3830 - SplFileObject::next example
  • Example#3831 - SplFileObject::rewind example
  • Example#3832 - SplFileObject::seek example
  • Example#3833 - SplFileObject::setCsvControl example
  • Example#3834 - SplFileObject::setFlags example
  • Example#3835 - SplFileObject::setMaxLineLen example
  • Example#3836 - SplFileObject::valid example
  • Example#3837 - SplTempFileObject example
  • Example#3838 - ArrayObject::append example
  • Example#3839 - ArrayObject::asort example
  • Example#3840 - ArrayObject::__construct example
  • Example#3841 - ArrayObject::count example
  • Example#3842 - ArrayObject::exchangeArray example
  • Example#3843 - ArrayObject::getArrayCopy example
  • Example#3844 - ArrayObject::getFlags example
  • Example#3845 - ArrayObject::getIterator example
  • Example#3846 - ArrayObject::getIteratorClass example
  • Example#3847 - ArrayObject::ksort example
  • Example#3848 - ArrayObject::natcasesort example
  • Example#3849 - ArrayObject::natsort example
  • Example#3850 - ArrayObject::offsetExists example
  • Example#3851 - ArrayObject::offsetGet example
  • Example#3852 - ArrayObject::offsetSet example
  • Example#3853 - ArrayObject::offsetUnset example
  • Example#3854 - ArrayObject::serialize example
  • Example#3855 - ArrayObject::setFlags example
  • Example#3856 - ArrayObject::setIteratorClass example
  • Example#3857 - ArrayObject::uasort example
  • Example#3858 - ArrayObject::uksort example
  • Example#3859 - Using file_get_contents to retrieve data from multiple sources
  • Example#3860 - Making a POST request to an https server
  • Example#3861 - Writing data to a compressed file
  • Example#3862 - A Stream for reading/writing global variables
  • Example#3863 - Listing files from tar archives
  • Example#3864 - stream_bucket_prepend examples
  • Example#3865 - Using stream_context_create
  • Example#3866 - Using stream_context_get_default
  • Example#3867 - stream_context_get_options example
  • Example#3868 - stream_context_get_params example
  • Example#3869 - stream_context_set_default example
  • Example#3870 - stream_context_set_options example
  • Example#3871 - A stream_copy_to_stream example
  • Example#3872 - Controlling where filters are applied
  • Example#3873 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#3874 - Registering a generic filter class to match multiple filter names.
  • Example#3875 - Dynamically refiltering a stream
  • Example#3876 - stream_get_contents example
  • Example#3877 - Using stream_get_filters
  • Example#3878 - stream_get_meta_data example using fopen with http
  • Example#3879 - stream_get_meta_data example using stream_socket_client with https
  • Example#3880 - Using stream_get_transports
  • Example#3881 - stream_get_wrappers example
  • Example#3882 - Checking for the existence of a stream wrapper
  • Example#3883 - stream_is_local example
  • Example#3884 - stream_isatty example
  • Example#3885 - stream_notification_callback example
  • Example#3886 - Simple progressbar for commandline download client
  • Example#3887 - stream_resolve_include_path example
  • Example#3888 - stream_select Example
  • Example#3889 - stream_set_timeout example
  • Example#3890 - stream_set_write_buffer example
  • Example#3891 - stream_socket_client example
  • Example#3892 - Using UDP connection
  • Example#3893 - stream_socket_enable_crypto example
  • Example#3894 - A stream_socket_pair example
  • Example#3895 - stream_socket_recvfrom example
  • Example#3896 - stream_socket_sendto Example
  • Example#3897 - Using TCP server sockets
  • Example#3898 - Using UDP server sockets
  • Example#3899 - A stream_socket_shutdown example
  • Example#3900 - How to register a stream wrapper
  • Example#3901 - Basic Tidy usage
  • Example#3902 - tidy::getBody example
  • Example#3903 - tidy::cleanrepair example
  • Example#3904 - tidy::__construct example
  • Example#3905 - tidy::diagnose example
  • Example#3906 - tidy_get_error_buffer example
  • Example#3907 - tidy::getConfig example
  • Example#3908 - tidy_getopt example
  • Example#3909 - Print all options along with their documentation and default value
  • Example#3910 - tidy::getStatus example
  • Example#3911 - tidy::head example
  • Example#3912 - tidy::html example
  • Example#3913 - tidy::parseFile example
  • Example#3914 - tidy::parseString example
  • Example#3915 - tidy::repairFile example
  • Example#3916 - tidy::repairString example
  • Example#3917 - tidy::root example
  • Example#3918 - tidyNode::hasChildren example
  • Example#3919 - tidyNode::hasChildren example
  • Example#3920 - tidyNode::hasSiblings example
  • Example#3921 - Extract ASP code from a mixed HTML document
  • Example#3922 - Extract comments from a mixed HTML document
  • Example#3923 - Extract HTML code from a mixed HTML document
  • Example#3924 - Extract JSTE code from a mixed HTML document
  • Example#3925 - Extract PHP code from a mixed HTML document
  • Example#3926 - Extract text from a mixed HTML document
  • Example#3927 - ob_tidyhandler example
  • Example#3928 - tidy_access_count example
  • Example#3929 - tidy_config_count example
  • Example#3930 - tidy_error_count example
  • Example#3931 - tidy_get_output example
  • Example#3932 - tidy_warning_count example
  • Example#3933 - Strip comments with the tokenizer
  • Example#3934 - PhpToken::getTokenName example
  • Example#3935 - PhpToken::is example
  • Example#3936 - Usage with array
  • Example#3937 - PhpToken::isIgnorable example
  • Example#3938 - PhpToken::__toString example
  • Example#3939 - PhpToken::tokenize example
  • Example#3940 - Extending PhpToken
  • Example#3941 - token_get_all example
  • Example#3942 - token_get_all incorrect usage example
  • Example#3943 - token_get_all on a class using a reserved word example
  • Example#3944 - token_name example
  • Example#3945 - base64_decode example
  • Example#3946 - base64_encode example
  • Example#3947 - get_headers example
  • Example#3948 - get_headers using HEAD example
  • Example#3949 - What get_meta_tags parses
  • Example#3950 - What get_meta_tags returns
  • Example#3951 - Simple usage of http_build_query
  • Example#3952 - http_build_query with numerically index elements.
  • Example#3953 - http_build_query with complex arrays
  • Example#3954 - Using http_build_query with an object
  • Example#3955 - A parse_url example
  • Example#3956 - A parse_url example with missing scheme
  • Example#3957 - rawurldecode example
  • Example#3958 - including a password in an FTP URL
  • Example#3959 - rawurlencode example 2
  • Example#3960 - urldecode example
  • Example#3961 - urlencode example
  • Example#3962 - urlencode and htmlentities example
  • Example#3963 - Basic Javascript execution
  • Example#3964 - Yaml Example
  • Example#3965 - Parse callback example
  • Example#3966 - Emit callback example
  • Example#3967 - yaml_emit example
  • Example#3968 - yaml_parse example
  • Example#3969 - A classic Application directory layout
  • Example#3970 - Entry
  • Example#3971 - Rewrite rule
  • Example#3972 - Application config
  • Example#3973 - Default controller
  • Example#3974 - Default view template
  • Example#3975 - Run the Application
  • Example#3976 - An PHP array example
  • Example#3977 - An ini file example
  • Example#3978 - A Bootstrapexample
  • Example#3979 - Yaf_Application::bootstrapexample
  • Example#3980 - Yaf_Application::clearLastErrorexample
  • Example#3981 - A ini config file example
  • Example#3982 - Yaf_Application::__constructexample
  • Example#3983 - Yaf_Application::__constructexample
  • Example#3984 - Yaf_Application::environexample
  • Example#3985 - Yaf_Application::executeexample
  • Example#3986 - Yaf_Application::getConfigexample
  • Example#3987 - Yaf_Application::getDispatcherexample
  • Example#3988 - Yaf_Application::getLastErrorMsgexample
  • Example#3989 - Yaf_Application::getLastErrorNoexample
  • Example#3990 - Yaf_Application::getModulesexample
  • Example#3991 - Bootstrap example
  • Example#3992 - Yaf_Dispatcher::autoRender example
  • Example#3993 - Yaf_Dispatcher::catchException example
  • Example#3994 - Yaf_Dispatcher::registerPlugin example
  • Example#3995 - A custom View engine example
  • Example#3996 - Yaf_Dispatcher::setView example
  • Example#3997 - Yaf_Dispatcher::throwexception example
  • Example#3998 - Yaf_Dispatcher::throwexceptionexample
  • Example#3999 - Yaf_Config_Iniexample
  • Example#4000 - define action in a separate file
  • Example#4001 - Dummy_action.php
  • Example#4002 - Yaf_Controller_Abstract::forwardexample
  • Example#4003 - Yaf_Action_Abstract::executeexample
  • Example#4004 - Yaf_Action_Abstract::executeexample
  • Example#4005 - Yaf_View_Simple::assignexample
  • Example#4006 - templateexample
  • Example#4007 - Yaf_View_Simple::assignRefexample
  • Example#4008 - templateexample
  • Example#4009 - Yaf_View_Simple::clearexample
  • Example#4010 - Yaf_View_Simple::__constructorexample
  • Example#4011 - Yaf_View_Simple::__setexample
  • Example#4012 - Config example
  • Example#4013 - Register localnamespace
  • Example#4014 - Load class example
  • Example#4015 - Load namespace class example
  • Example#4016 - MVC class loading example
  • Example#4017 - MVC class distinctions
  • Example#4018 - MVC loading example
  • Example#4019 - Yaf_Loader::registerNamespaceexample
  • Example#4020 - Yaf_Loader::registerLocalNamespaceexample
  • Example#4021 - Yaf_Loader::registerNamespaceexample
  • Example#4022 - Plugin example
  • Example#4023 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#4024 - Yaf_Response_Abstract::appendBodyexample
  • Example#4025 - Yaf_Response_Abstract::getBodyexample
  • Example#4026 - Yaf_Response_Abstract::prependBodyexample
  • Example#4027 - Yaf_Response_Abstract::responseexample
  • Example#4028 - Yaf_Response_Abstract::setBodyexample
  • Example#4029 - Yaf_Route_Map::assembleexample
  • Example#4030 - Yaf_Route_Mapexample
  • Example#4031 - Yaf_Route_Mapexample
  • Example#4032 - Yaf_Route_Mapexample
  • Example#4033 - Yaf_Route_Regex::assembleexample
  • Example#4034 - Yaf_Route_Regexexample
  • Example#4035 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#4036 - Yaf_Route_Regex and named capture ground(as of 2.3.0)example
  • Example#4037 - Yaf_Route_Regexexample
  • Example#4038 - Yaf_Route_Rewrite::assembleexample
  • Example#4039 - Yaf_Route_Rewriteexample
  • Example#4040 - Yaf_Route_Rewriteexample
  • Example#4041 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#4042 - Rewrite rule for Apache
  • Example#4043 - Rewrite rule for Apache
  • Example#4044 - Rewrite rule for Lighttpd
  • Example#4045 - Rewrite rule for Nginx
  • Example#4046 - Yaf_Route_Static(default route)example
  • Example#4047 - application.iniexample
  • Example#4048 - Yaf_Dispatcher::autoConfigexample
  • Example#4049 - Yaf_Dispatcher::autoRenderexample
  • Example#4050 - Register some routes in Bootstrap
  • Example#4051 - plugin Dummy.php (under application.directory/plugins)
  • Example#4052 - Yaf_Route_Simple::assembleexample
  • Example#4053 - Yaf_Route_Simple::routeexample
  • Example#4054 - Yaf_Route_Simple::routeexample
  • Example#4055 - Yaf_Route_Static::assembleexample
  • Example#4056 - Yaf_Route_Static::routeexample
  • Example#4057 - Yaf_Route_Supervar::assemble example
  • Example#4058 - Yaf_Route_Supervarexample
  • Example#4059 - INI example
  • Example#4060 - INI sections example
  • Example#4061 - INIexample
  • Example#4062 - Taintexample
  • Example#4063 - Vector
  • Example#4064 - Map
  • Example#4065 - Ds\Collection::clear example
  • Example#4066 - Ds\Collection::copy example
  • Example#4067 - Ds\Collection::isEmpty example
  • Example#4068 - Ds\Collection::toArray example
  • Example#4069 - Ds\Hashable::hash example
  • Example#4070 - Ds\Sequence::allocate example
  • Example#4071 - Ds\Sequence::apply example
  • Example#4072 - Ds\Sequence::capacity example
  • Example#4073 - Ds\Sequence::contains example
  • Example#4074 - Ds\Sequence::filter example using callback function
  • Example#4075 - Ds\Sequence::filter example without a callback function
  • Example#4076 - Ds\Sequence::find example
  • Example#4077 - Ds\Sequence::first example
  • Example#4078 - Ds\Sequence::get example
  • Example#4079 - Ds\Sequence::get example using array syntax
  • Example#4080 - Ds\Sequence::insert example
  • Example#4081 - Ds\Sequence::join example using a separator string
  • Example#4082 - Ds\Sequence::join example without a separator string
  • Example#4083 - Ds\Sequence::last example
  • Example#4084 - Ds\Sequence::map example
  • Example#4085 - Ds\Sequence::merge example
  • Example#4086 - Ds\Sequence::pop example
  • Example#4087 - Ds\Sequence::push example
  • Example#4088 - Ds\Sequence::reduce with initial value example
  • Example#4089 - Ds\Sequence::reduce without an initial value example
  • Example#4090 - Ds\Sequence::remove example
  • Example#4091 - Ds\Sequence::reverse example
  • Example#4092 - Ds\Sequence::reversed example
  • Example#4093 - Ds\Sequence::rotate example
  • Example#4094 - Ds\Sequence::set example
  • Example#4095 - Ds\Sequence::set example using array syntax
  • Example#4096 - Ds\Sequence::shift example
  • Example#4097 - Ds\Sequence::slice example
  • Example#4098 - Ds\Sequence::sort example
  • Example#4099 - Ds\Sequence::sort example using a comparator
  • Example#4100 - Ds\Sequence::sorted example
  • Example#4101 - Ds\Sequence::sorted example using a comparator
  • Example#4102 - Ds\Sequence::sum integer example
  • Example#4103 - Ds\Sequence::sum float example
  • Example#4104 - Ds\Sequence::unshift example
  • Example#4105 - Ds\Vector::allocate example
  • Example#4106 - Ds\Vector::apply example
  • Example#4107 - Ds\Vector::capacity example
  • Example#4108 - Ds\Vector::clear example
  • Example#4109 - Ds\Vector::__construct example
  • Example#4110 - Ds\Vector::contains example
  • Example#4111 - Ds\Vector::copy example
  • Example#4112 - Ds\Vector::filter example using callback function
  • Example#4113 - Ds\Vector::filter example without a callback function
  • Example#4114 - Ds\Vector::find example
  • Example#4115 - Ds\Vector::first example
  • Example#4116 - Ds\Vector::get example
  • Example#4117 - Ds\Vector::get example using array syntax
  • Example#4118 - Ds\Vector::insert example
  • Example#4119 - Ds\Vector::isEmpty example
  • Example#4120 - Ds\Vector::join example using a separator string
  • Example#4121 - Ds\Vector::join example without a separator string
  • Example#4122 - Ds\Vector::last example
  • Example#4123 - Ds\Vector::map example
  • Example#4124 - Ds\Vector::merge example
  • Example#4125 - Ds\Vector::pop example
  • Example#4126 - Ds\Vector::push example
  • Example#4127 - Ds\Vector::reduce with initial value example
  • Example#4128 - Ds\Vector::reduce without an initial value example
  • Example#4129 - Ds\Vector::remove example
  • Example#4130 - Ds\Vector::reverse example
  • Example#4131 - Ds\Vector::reversed example
  • Example#4132 - Ds\Vector::rotate example
  • Example#4133 - Ds\Vector::set example
  • Example#4134 - Ds\Vector::set example using array syntax
  • Example#4135 - Ds\Vector::shift example
  • Example#4136 - Ds\Vector::slice example
  • Example#4137 - Ds\Vector::sort example
  • Example#4138 - Ds\Vector::sort example using a comparator
  • Example#4139 - Ds\Vector::sorted example
  • Example#4140 - Ds\Vector::sorted example using a comparator
  • Example#4141 - Ds\Vector::sum integer example
  • Example#4142 - Ds\Vector::sum float example
  • Example#4143 - Ds\Vector::toArray example
  • Example#4144 - Ds\Vector::unshift example
  • Example#4145 - Ds\Deque::allocate example
  • Example#4146 - Ds\Deque::apply example
  • Example#4147 - Ds\Deque::capacity example
  • Example#4148 - Ds\Deque::clear example
  • Example#4149 - Ds\Deque::__construct example
  • Example#4150 - Ds\Deque::contains example
  • Example#4151 - Ds\Deque::copy example
  • Example#4152 - Ds\Deque::filter example using callback function
  • Example#4153 - Ds\Deque::filter example without a callback function
  • Example#4154 - Ds\Deque::find example
  • Example#4155 - Ds\Deque::first example
  • Example#4156 - Ds\Deque::get example
  • Example#4157 - Ds\Deque::get example using array syntax
  • Example#4158 - Ds\Deque::insert example
  • Example#4159 - Ds\Deque::isEmpty example
  • Example#4160 - Ds\Deque::join example using a separator string
  • Example#4161 - Ds\Deque::join example without a separator string
  • Example#4162 - Ds\Deque::last example
  • Example#4163 - Ds\Deque::map example
  • Example#4164 - Ds\Deque::merge example
  • Example#4165 - Ds\Deque::pop example
  • Example#4166 - Ds\Deque::push example
  • Example#4167 - Ds\Deque::reduce with initial value example
  • Example#4168 - Ds\Deque::reduce without an initial value example
  • Example#4169 - Ds\Deque::remove example
  • Example#4170 - Ds\Deque::reverse example
  • Example#4171 - Ds\Deque::reversed example
  • Example#4172 - Ds\Deque::rotate example
  • Example#4173 - Ds\Deque::set example
  • Example#4174 - Ds\Deque::set example using array syntax
  • Example#4175 - Ds\Deque::shift example
  • Example#4176 - Ds\Deque::slice example
  • Example#4177 - Ds\Deque::sort example
  • Example#4178 - Ds\Deque::sort example using a comparator
  • Example#4179 - Ds\Deque::sorted example
  • Example#4180 - Ds\Deque::sorted example using a comparator
  • Example#4181 - Ds\Deque::sum integer example
  • Example#4182 - Ds\Deque::sum float example
  • Example#4183 - Ds\Deque::toArray example
  • Example#4184 - Ds\Deque::unshift example
  • Example#4185 - Ds\Map::allocate example
  • Example#4186 - Ds\Map::apply example
  • Example#4187 - Ds\Map::capacity example
  • Example#4188 - Ds\Map::clear example
  • Example#4189 - Ds\Map::__construct example
  • Example#4190 - Ds\Map::copy example
  • Example#4191 - Ds\Map::diff example
  • Example#4192 - Ds\Map::filter example using callback function
  • Example#4193 - Ds\Map::filter example without a callback function
  • Example#4194 - Ds\Map::first example
  • Example#4195 - Ds\Map::get example
  • Example#4196 - Ds\Map::get example using array syntax
  • Example#4197 - Ds\Map::hasKey example
  • Example#4198 - Ds\Map::hasValue example
  • Example#4199 - Ds\Map::intersect example
  • Example#4200 - Ds\Map::isEmpty example
  • Example#4201 - Ds\Map::keys example
  • Example#4202 - Ds\Map::ksort example
  • Example#4203 - Ds\Map::ksort example using a comparator
  • Example#4204 - Ds\Map::ksorted example
  • Example#4205 - Ds\Map::ksorted example using a comparator
  • Example#4206 - Ds\Map::last example
  • Example#4207 - Ds\Map::map example
  • Example#4208 - Ds\Map::merge example
  • Example#4209 - Ds\Map::pairs example
  • Example#4210 - Ds\Map::put example
  • Example#4211 - Ds\Map::put example using objects as keys
  • Example#4212 - Ds\Map::putAll example
  • Example#4213 - Ds\Map::reduce with initial value example
  • Example#4214 - Ds\Map::reduce without an initial value example
  • Example#4215 - Ds\Map::remove example
  • Example#4216 - Ds\Map::reverse example
  • Example#4217 - Ds\Map::reversed example
  • Example#4218 - Ds\Map::skip example
  • Example#4219 - Ds\Map::slice example
  • Example#4220 - Ds\Map::sort example
  • Example#4221 - Ds\Map::sort example using a comparator
  • Example#4222 - Ds\Map::sort example
  • Example#4223 - Ds\Map::sort example using a comparator
  • Example#4224 - Ds\Map::sum integer example
  • Example#4225 - Ds\Map::sum float example
  • Example#4226 - Ds\Map::toArray example
  • Example#4227 - Ds\Map::union example
  • Example#4228 - Ds\Map::values example
  • Example#4229 - Ds\Map::xor example
  • Example#4230 - Ds\Pair::clear example
  • Example#4231 - Ds\Pair::copy example
  • Example#4232 - Ds\Pair::isEmpty example
  • Example#4233 - Ds\Pair::toArray example
  • Example#4234 - Ds\Set::add example using integers
  • Example#4235 - Ds\Set::add example using objects
  • Example#4236 - Ds\Set::allocate example
  • Example#4237 - Ds\Set::capacity example
  • Example#4238 - Ds\Set::clear example
  • Example#4239 - Ds\Set::__construct example
  • Example#4240 - Ds\Set::contains example
  • Example#4241 - Ds\Set::copy example
  • Example#4242 - Ds\Set::diff example
  • Example#4243 - Ds\Set::filter example using callback function
  • Example#4244 - Ds\Set::filter example without a callback function
  • Example#4245 - Ds\Set::first example
  • Example#4246 - Ds\Set::get example
  • Example#4247 - Ds\Set::get example using array syntax
  • Example#4248 - Ds\Set::intersect example
  • Example#4249 - Ds\Set::isEmpty example
  • Example#4250 - Ds\Set::join example using a separator string
  • Example#4251 - Ds\Set::join example without a separator string
  • Example#4252 - Ds\Set::last example
  • Example#4253 - Ds\Set::merge example
  • Example#4254 - Ds\Set::reduce with initial value example
  • Example#4255 - Ds\Set::reduce without an initial value example
  • Example#4256 - Ds\Set::remove example
  • Example#4257 - Ds\Set::reverse example
  • Example#4258 - Ds\Set::reversed example
  • Example#4259 - Ds\Set::slice example
  • Example#4260 - Ds\Set::sort example
  • Example#4261 - Ds\Set::sort example using a comparator
  • Example#4262 - Ds\Set::sorted example
  • Example#4263 - Ds\Set::sorted example using a comparator
  • Example#4264 - Ds\Set::sum integer example
  • Example#4265 - Ds\Set::sum float example
  • Example#4266 - Ds\Set::toArray example
  • Example#4267 - Ds\Set::union example
  • Example#4268 - Ds\Set::xor example
  • Example#4269 - Ds\Stack::clear example
  • Example#4270 - Ds\Stack::__construct example
  • Example#4271 - Ds\Stack::copy example
  • Example#4272 - Ds\Stack::isEmpty example
  • Example#4273 - Ds\Stack::peek example
  • Example#4274 - Ds\Stack::pop example
  • Example#4275 - Ds\Stack::push example
  • Example#4276 - Ds\Stack::toArray example
  • Example#4277 - Ds\Queue::allocate example
  • Example#4278 - Ds\Queue::capacity example
  • Example#4279 - Ds\Queue::clear example
  • Example#4280 - Ds\Queue::__construct example
  • Example#4281 - Ds\Queue::copy example
  • Example#4282 - Ds\Queue::isEmpty example
  • Example#4283 - Ds\Queue::peek example
  • Example#4284 - Ds\Queue::pop example
  • Example#4285 - Ds\Queue::push example
  • Example#4286 - Ds\Queue::toArray example
  • Example#4287 - Ds\PriorityQueue::allocate example
  • Example#4288 - Ds\PriorityQueue::capacity example
  • Example#4289 - Ds\PriorityQueue::clear example
  • Example#4290 - Ds\PriorityQueue::__construct example
  • Example#4291 - Ds\PriorityQueue::copy example
  • Example#4292 - Ds\PriorityQueue::isEmpty example
  • Example#4293 - Ds\PriorityQueue::peek example
  • Example#4294 - Ds\PriorityQueue::pop example
  • Example#4295 - Ds\PriorityQueue::push example
  • Example#4296 - Ds\PriorityQueue::toArray example
  • Example#4297 - var_representation Examples
  • Example#4298 - Escaping control characters
  • Example#4299 - Exporting stdClass
  • Example#4300 - Exporting classes
  • Example#4301 - Using __set_state()
  • Example#4302 - Using PHP's cURL module to fetch the example.com homepage
  • Example#4303 - Initializing a new cURL session and fetching a web page
  • Example#4304 - Copying a cURL handle
  • Example#4305 - curl_errno example
  • Example#4306 - curl_error example
  • Example#4307 - curl_escape example
  • Example#4308 - Fetching a web page
  • Example#4309 - curl_getinfo example
  • Example#4310 - curl_getinfo example with option parameter
  • Example#4311 - Initializing a new cURL session and fetching a web page
  • Example#4312 - curl_multi_add_handle example
  • Example#4313 - curl_multi_close example
  • Example#4314 - curl_multi_exec example
  • Example#4315 - A curl_multi_info_read example
  • Example#4316 - curl_multi_init example
  • Example#4317 - curl_multi_strerror example
  • Example#4318 - curl_reset example
  • Example#4319 - Initializing a new cURL session and fetching a web page
  • Example#4320 - Initializing a new cURL session and fetching a web page
  • Example#4321 - curl_share_setopt example
  • Example#4322 - curl_share_init example
  • Example#4323 - curl_share_setopt example
  • Example#4324 - curl_errno example
  • Example#4325 - curl_escape example
  • Example#4326 - curl_upkeep example
  • Example#4327 - curl_version example
  • Example#4328 - CURLFile::__construct example
  • Example#4329 - CURLFile::__construct uploading multiple files example
  • Example#4330 - CURLStringFile::__construct example
  • Example#4331 - Simple HTTP client
  • Example#4332 - HTTP client using asynchronous DNS resolver
  • Example#4333 - Echo server
  • Example#4334 - SSL echo server
  • Example#4335 - Signal handler
  • Example#4336 - Use libevent's loop to process requests of `eio' extension
  • Example#4337 - Miscellaneous
  • Example#4338 - Simple HTTP server
  • Example#4339 - Simple HTTPS server
  • Example#4340 - OpenSSL connection
  • Example#4341 - EventHttpConnection::makeRequest example
  • Example#4342 - Connection listener based on a UNIX domain socket
  • Example#4343 - Simple SMTP server
  • Example#4344 - Handling SIGTERM signal
  • Example#4345 - Adding a custom signal
  • Example#4346 - Adding a timer
  • Example#4347 - EventBase::getFeatures example
  • Example#4348 - EventBase::getMethod example
  • Example#4349 - EventBuffer::search example
  • Example#4350 - EventBufferEvent::connect example
  • Example#4351 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4352 - EventBufferEvent::connectHost example
  • Example#4353 - Buffer event's read callback
  • Example#4354 - EventBufferEvent::getOutput example
  • Example#4355 - EventBufferEvent::sslError example
  • Example#4356 - Simple SMTP server
  • Example#4357 - EventConfig::avoidMethod example
  • Example#4358 - EventConfig::__construct example
  • Example#4359 - EventConfig::requireFeatures example
  • Example#4360 - EventHttp::accept example
  • Example#4361 - EventHttp::addServerAlias example
  • Example#4362 - EventHttp::bind example
  • Example#4363 - Simple HTTP server
  • Example#4364 - EventHttp::setCallback example
  • Example#4365 - EventHttp::setDefaultCallback example
  • Example#4366 - EventHttpConnection::makeRequest example
  • Example#4367 - EventHttpConnection::setCloseCallback example
  • Example#4368 - EventHttpRequest::__construct example
  • Example#4369 - EventHttpRequest::sendError example
  • Example#4370 - EventListener::__construct example
  • Example#4371 - EventSslContext::__construct example
  • Example#4372 - FTP example
  • Example#4373 - ftp_alloc example
  • Example#4374 - ftp_cdup example
  • Example#4375 - ftp_chdir example
  • Example#4376 - ftp_chmod example
  • Example#4377 - ftp_close example
  • Example#4378 - ftp_connect example
  • Example#4379 - ftp_delete example
  • Example#4380 - ftp_exec example
  • Example#4381 - ftp_fget example
  • Example#4382 - ftp_fput example
  • Example#4383 - ftp_get_option example
  • Example#4384 - ftp_get example
  • Example#4385 - ftp_login example
  • Example#4386 - ftp_mdtm example
  • Example#4387 - ftp_mkdir example
  • Example#4388 - ftp_mlsd example
  • Example#4389 - ftp_nb_continue example
  • Example#4390 - ftp_nb_fget example
  • Example#4391 - ftp_nb_fput example
  • Example#4392 - ftp_nb_get example
  • Example#4393 - Resuming a download with ftp_nb_get
  • Example#4394 - Resuming a download at position 100 to a new file with ftp_nb_get
  • Example#4395 - ftp_nb_put example
  • Example#4396 - Resuming an upload with ftp_nb_put
  • Example#4397 - ftp_nlist example
  • Example#4398 - ftp_pasv example
  • Example#4399 - ftp_put example
  • Example#4400 - ftp_pwd example
  • Example#4401 - Using ftp_raw to login to an FTP server manually.
  • Example#4402 - ftp_rawlist example
  • Example#4403 - ftp_rename example
  • Example#4404 - ftp_rmdir example
  • Example#4405 - ftp_set_option example
  • Example#4406 - Sending a SITE command to an ftp server
  • Example#4407 - ftp_size example
  • Example#4408 - ftp_ssl_connect example
  • Example#4409 - ftp_systype example
  • Example#4410 - Basic Gearman client and worker
  • Example#4411 - Basic Gearman client and worker, background
  • Example#4412 - Basic Gearman client and worker, submitting tasks
  • Example#4413 - Adding two job servers
  • Example#4414 - Add two job servers
  • Example#4415 - Basic submission of two tasks
  • Example#4416 - Basic submission of two tasks with passing application context
  • Example#4417 - Two tasks, one background and one not
  • Example#4418 - A high priority task along with two normal tasks
  • Example#4419 - A low priority task along with two normal tasks
  • Example#4420 - Monitor completion of multiple background tasks
  • Example#4421 - Simple job submission with immediate return
  • Example#4422 - Submitting a job and retrieving incremental status
  • Example#4423 - Submit and monitor a background job
  • Example#4424 - Simple job submission with immediate return
  • Example#4425 - Submitting a job and retrieving incremental status
  • Example#4426 - Get the status of a long running job
  • Example#4427 - Monitor the status of a long running background job
  • Example#4428 - Simple worker making use of extra application context data
  • Example#4429 - Add alternate Gearman servers
  • Example#4430 - Add two job servers
  • Example#4431 - GearmanWorker::setId example
  • Example#4432 - A simple worker with a 5 second timeout
  • Example#4433 - Running worker in non-blocking mode
  • Example#4434 - GearmanWorker::work example
  • Example#4435 - Testing support for paged result control
  • Example#4436 - LDAP search example
  • Example#4437 - Bind with policy information
  • Example#4438 - Modify description only if it's not empty
  • Example#4439 - Read some values before deletion
  • Example#4440 - Delete a reference
  • Example#4441 - Use pagination for a search
  • Example#4442 - Complete example with authenticated bind
  • Example#4443 - Using LDAP Bind
  • Example#4444 - Using LDAP Bind Anonymously
  • Example#4445 - Complete example of password check
  • Example#4446 - Example of connecting to LDAP server.
  • Example#4447 - Example of connecting securely to LDAP server.
  • Example#4448 - LDAP pagination
  • Example#4449 - LDAP pagination
  • Example#4450 - ldap_count_entries example
  • Example#4451 - Enumerating all LDAP error messages
  • Example#4452 - Generating and catching an error
  • Example#4453 - Searching for an email address
  • Example#4454 - PASSWD extended operation
  • Example#4455 - Whoami extended operation
  • Example#4456 - Show the list of attributes held for a particular directory entry
  • Example#4457 - Check protocol version
  • Example#4458 - List all values of the "mail" attribute for a directory entry
  • Example#4459 - Produce a list of all organizational units of an organization
  • Example#4460 - Add a telephone number to a contact
  • Example#4461 - Rename a user
  • Example#4462 - Add two e-mail addresses to a user
  • Example#4463 - Change a user's password
  • Example#4464 - Change a user's password (Active Directory)
  • Example#4465 - ldap_parse_result example
  • Example#4466 - LDAP search
  • Example#4467 - Set protocol version
  • Example#4468 - Set server controls
  • Example#4469 - LDAP sort
  • Example#4470 - memcache extension overview example
  • Example#4471 - Using memcache session handler
  • Example#4472 - Memcache::add example
  • Example#4473 - Memcache::addServer example
  • Example#4474 - Memcache::close example
  • Example#4475 - Memcache::connect example
  • Example#4476 - Memcache::decrement example
  • Example#4477 - Memcache::delete example
  • Example#4478 - Memcache::flush example
  • Example#4479 - Memcache::get example
  • Example#4480 - Memcache::getExtendedStats example
  • Example#4481 - Memcache::getServerStatus example
  • Example#4482 - Memcache::getVersion example
  • Example#4483 - Memcache::increment example
  • Example#4484 - Memcache::pconnect example
  • Example#4485 - Memcache::replace example
  • Example#4486 - Memcache::set example
  • Example#4487 - Memcache::set example
  • Example#4488 - Memcache::setCompressThreshold example
  • Example#4489 - Memcache::setServerParams example
  • Example#4490 - Result callback example
  • Example#4491 - Read-through callback example
  • Example#4492 - Memcached::addServer example
  • Example#4493 - Memcached::addServers example
  • Example#4494 - Memcached::append example
  • Example#4495 - Memcached::cas example
  • Example#4496 - Creating a Memcached object
  • Example#4497 - Memcached::decrement example
  • Example#4498 - Memcached::delete example
  • Example#4499 - Memcached::fetch example
  • Example#4500 - Memcached::getDelayed example
  • Example#4501 - Memcached::flush example
  • Example#4502 - Memcached::get example #1
  • Example#4503 - Memcached::get example #2
  • Example#4504 - Memcached::getDelayed example
  • Example#4505 - Memcached::getMulti example for Memcached v3
  • Example#4506 - Memcached::getMulti example for Memcached v1 and v2
  • Example#4507 - Memcached::GET_PRESERVE_ORDER example for Memcached v3
  • Example#4508 - Memcached::GET_PRESERVE_ORDER example for Memcached v1 and v2
  • Example#4509 - Retrieving Memcached options
  • Example#4510 - Memcached::getResultCode example
  • Example#4511 - Memcached::getResultMessage example
  • Example#4512 - Memcached::getServerByKey example
  • Example#4513 - Memcached::getServerList example
  • Example#4514 - Memcached::getStats example
  • Example#4515 - Memcached::getVersion example
  • Example#4516 - Memcached::increment example
  • Example#4517 - Memcached::prepend example
  • Example#4518 - Memcached::set example
  • Example#4519 - Memcached::setByKey example
  • Example#4520 - Memcached::setMulti example
  • Example#4521 - Setting a Memcached option
  • Example#4522 - Setting Memcached options
  • Example#4523 - mqseries_back example
  • Example#4524 - mqseries_begin example
  • Example#4525 - mqseries_close example
  • Example#4526 - mqseries_cmit example
  • Example#4527 - mqseries_conn example
  • Example#4528 - mqseries_connx example
  • Example#4529 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4530 - mqseries_disc example
  • Example#4531 - mqseries_get example
  • Example#4532 - mqseries_inq example
  • Example#4533 - mqseries_open example
  • Example#4534 - mqseries_put example
  • Example#4535 - mqseries_strerror example
  • Example#4536 - Using dns_get_record
  • Example#4537 - Using dns_get_record and DNS_ANY
  • Example#4538 - fsockopen Example
  • Example#4539 - Using UDP connection
  • Example#4540 - A simple gethostbyaddr example
  • Example#4541 - A simple gethostbyname example
  • Example#4542 - gethostbynamel example
  • Example#4543 - A simple gethostname example
  • Example#4544 - getprotobyname example
  • Example#4545 - getservbyname example
  • Example#4546 - header_register_callback example
  • Example#4547 - Unsetting specific header.
  • Example#4548 - Unsetting all previously set headers.
  • Example#4549 - Download dialog
  • Example#4550 - Caching directives
  • Example#4551 - Example using headers_list
  • Example#4552 - Examples using headers_sent
  • Example#4553 - Using http_response_code in a web server environment
  • Example#4554 - Using http_response_code in a CLI environment
  • Example#4555 - inet_ntop Example
  • Example#4556 - inet_pton Example
  • Example#4557 - ip2long Example
  • Example#4558 - Displaying an IP address
  • Example#4559 - setcookie send example
  • Example#4560 - setcookie delete example
  • Example#4561 - setcookie and arrays
  • Example#4562 - Using syslog
  • Example#4563 - Procedural usage of rrd
  • Example#4564 - OO usage of rrd
  • Example#4565 - RRDGraph::setOptions example
  • Example#4566 - Set multiple color options
  • Example#4567 - RRDUpdater::update examples
  • Example#4568 - Fetch instrumented calls
  • Example#4569 - Fetch the list of functions scoutapm will instrument
  • Example#4570 - snmp_get_quick_print example
  • Example#4571 - Using snmp_get_valueretrieval
  • Example#4572 - Using snmp_read_mib
  • Example#4573 - Using snmp_set_enum_print
  • Example#4574 - Using snmprealwalk
  • Example#4575 - Using snmp_set_quick_print
  • Example#4576 - Using snmp_set_valueretrieval
  • Example#4577 - Using snmp2_get
  • Example#4578 - Using snmp2_get_next
  • Example#4579 - Using snmp2_real_walk
  • Example#4580 - Using snmp2_set
  • Example#4581 - Using snmp2_set for setting BITS SNMP object id
  • Example#4582 - snmp2_walk Example
  • Example#4583 - Using snmp3_get
  • Example#4584 - Using snmp3_getnext
  • Example#4585 - Using snmp3_real_walk
  • Example#4586 - Using snmp3_set
  • Example#4587 - Using snmp3_set for setting BITS SNMP object id
  • Example#4588 - snmp3_walk Example
  • Example#4589 - Using snmpget
  • Example#4590 - Using snmpgetnext
  • Example#4591 - Using snmprealwalk
  • Example#4592 - Using snmpset
  • Example#4593 - Using snmpset for setting BITS SNMP object id
  • Example#4594 - snmpwalk Example
  • Example#4595 - snmpwalkoid Example
  • Example#4596 - SNMP::close example
  • Example#4597 - Fetching sysLocation
  • Example#4598 - Single SNMP object
  • Example#4599 - Multiple SNMP objects
  • Example#4600 - SNMP::getErrno example
  • Example#4601 - SNMP::getError example
  • Example#4602 - Single SNMP object
  • Example#4603 - Miltiple SNMP objects
  • Example#4604 - Set single SNMP object id
  • Example#4605 - Set multiple values using single SNMP::set call
  • Example#4606 - Using SNMP::set for setting BITS SNMP object id
  • Example#4607 - SNMP::setSecurity example
  • Example#4608 - SNMP::walk example
  • Example#4609 - suffixAsKey example
  • Example#4610 - Socket example: Simple TCP/IP server
  • Example#4611 - Socket example: Simple TCP/IP client
  • Example#4612 - Using socket_atmark to set the source address
  • Example#4613 - Using socket_bind to set the source address
  • Example#4614 - socket_create_pair example
  • Example#4615 - socket_create_pair IPC example
  • Example#4616 - socket_get_option example
  • Example#4617 - socket_import_stream example
  • Example#4618 - socket_last_error example
  • Example#4619 - socket_recv example
  • Example#4620 - socket_recvfrom example
  • Example#4621 - Using null with socket_select
  • Example#4622 - Understanding socket_select's result
  • Example#4623 - socket_select example
  • Example#4624 - socket_sendto Example
  • Example#4625 - socket_set_block example
  • Example#4626 - socket_set_nonblock example
  • Example#4627 - socket_set_option example
  • Example#4628 - socket_strerror example
  • Example#4629 - Authenticating with a ssh agent
  • Example#4630 - Authentication using a public hostkey
  • Example#4631 - Retrieving a list of authentication methods
  • Example#4632 - Authenticating with a password
  • Example#4633 - Authentication using a public key
  • Example#4634 - ssh2_connect example
  • Example#4635 - Executing a command
  • Example#4636 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4637 - Checking the fingerprint against a known value
  • Example#4638 - Determining what methods were negotiated
  • Example#4639 - Adding a publickey with ssh2_publickey_add
  • Example#4640 - Listing authorized keys with ssh2_publickey_list
  • Example#4641 - Downloading a file via SCP
  • Example#4642 - Uploading a file via SCP
  • Example#4643 - Changing the mode of a file on a remote server
  • Example#4644 - Stating a symbolic link via SFTP
  • Example#4645 - Creating a directory on a remote server
  • Example#4646 - Reading a symbolic link
  • Example#4647 - Resolving a pathname
  • Example#4648 - Renaming a file via sftp
  • Example#4649 - Removing a directory on a remote server
  • Example#4650 - Stating a file via SFTP
  • Example#4651 - Creating a symbolic link
  • Example#4652 - Deleting a file
  • Example#4653 - Opening a file via SFTP
  • Example#4654 - Requesting an interactive shell
  • Example#4655 - Opening a tunnel to an arbitrary host
  • Example#4656 - Object-oriented style
  • Example#4657 - Procedural style
  • Example#4658 - stomp_connect_error example
  • Example#4659 - stomp_version example
  • Example#4660 - Object-oriented style
  • Example#4661 - Procedural style
  • Example#4662 - Object-oriented style
  • Example#4663 - Procedural style
  • Example#4664 - Object-oriented style
  • Example#4665 - Procedural style
  • Example#4666 - Object-oriented style
  • Example#4667 - Procedural style
  • Example#4668 - Object-oriented style
  • Example#4669 - Procedural style
  • Example#4670 - Object-oriented style
  • Example#4671 - Procedural style
  • Example#4672 - Object-oriented style
  • Example#4673 - Procedural style
  • Example#4674 - Object-oriented style
  • Example#4675 - Procedural style
  • Example#4676 - Object-oriented style
  • Example#4677 - Procedural style
  • Example#4678 - Train from array
  • Example#4679 - Train from a file
  • Example#4680 - svn_add example
  • Example#4681 - Default authentication example
  • Example#4682 - svn_blame example
  • Example#4683 - Basic example
  • Example#4684 - Basic example
  • Example#4685 - Basic example
  • Example#4686 - Basic example
  • Example#4687 - Basic example
  • Example#4688 - Basic example
  • Example#4689 - Diffing two revisions of a repository path
  • Example#4690 - Portably diffing two local files
  • Example#4691 - svn_export example
  • Example#4692 - Basic example
  • Example#4693 - svn_log example
  • Example#4694 - svn_ls example
  • Example#4695 - Basic example
  • Example#4696 - Basic example
  • Example#4697 - Deny all connections from localhost
  • Example#4698 - Ban an URL
  • Example#4699 - Get statistic snapshot
  • Example#4700 - Read varnish shared memory log
  • Example#4701 - VarnishAdmin::__construct example
  • Example#4702 - Parallel searching using Yaz
  • Example#4703 - CCL configuration
  • Example#4704 - CCL Parsing
  • Example#4705 - Record Update
  • Example#4706 - Array for GRS-1 record
  • Example#4707 - Working with MARCXML
  • Example#4708 - PHP function that scans titles
  • Example#4709 - Query Examples
  • Example#4710 - Sort Criterias
  • Example#4711 - A ZMQContext example
  • Example#4712 - A ZMQContext example
  • Example#4713 - A ZMQContext example
  • Example#4714 - A ZMQSocket example
  • Example#4715 - A send/recv example
  • Example#4716 - A ZMQPoll example
  • Example#4717 - zookeeper_dispatch example #1
  • Example#4718 - zookeeper_dispatch example #2
  • Example#4719 - Zookeeper::addAuth example
  • Example#4720 - Zookeeper::create example
  • Example#4721 - Zookeeper::delete example
  • Example#4722 - Zookeeper::exists example
  • Example#4723 - Zookeeper::get example
  • Example#4724 - Zookeeper::get stat example
  • Example#4725 - Zookeeper::getAcl example
  • Example#4726 - Zookeeper::getChildren example
  • Example#4727 - Zookeeper::set example
  • Example#4728 - Zookeeper::setAcl example
  • Example#4729 - Zookeeper::setDebugLevel example
  • Example#4730 - ZookeeperConfig::add example
  • Example#4731 - ZookeeperConfig::get example
  • Example#4732 - ZookeeperConfig::remove example
  • Example#4733 - ZookeeperConfig::set example
  • Example#4734 - solr_get_version example
  • Example#4735 - Contents of the BootStrap file
  • Example#4736 - Adding a document to the index
  • Example#4737 - Merging one document into another document
  • Example#4738 - Searching for documents - SolrObject responses
  • Example#4739 - Searching for documents - SolrDocument responses
  • Example#4740 - Simple TermsComponent example - basic
  • Example#4741 - Simple TermsComponent example - using a prefix
  • Example#4742 - Simple TermsComponent example - specifying a minimum frequency
  • Example#4743 - Simple Facet Example
  • Example#4744 - Simple Facet Example - with optional field override for mincount
  • Example#4745 - Facet Date Example
  • Example#4746 - Connecting to SSL-Enabled Server
  • Example#4747 - Collapsing a SolrQuery
  • Example#4748 - Solr Real Time Get (RTG) example SolrClient::getById
  • Example#4749 - SolrInputDocument::addChildDocument example
  • Example#4750 - SolrInputDocument::addChildDocuments example
  • Example#4751 - SolrDocument::toArray example
  • Example#4752 - SolrObject::__construct example
  • Example#4753 - SolrObject::offsetUnset example
  • Example#4754 - SolrClient::addDocument example
  • Example#4755 - SolrClient::addDocument example 2
  • Example#4756 - SolrClient::addDocuments example
  • Example#4757 - SolrClient::__construct example
  • Example#4758 - SolrQuery::deleteByQuery example
  • Example#4759 - SolrClient::getById example
  • Example#4760 - SolrClient::getByIds example
  • Example#4761 - SolrClient::ping example
  • Example#4762 - SolrClient::query example
  • Example#4763 - SolrClient::request example
  • Example#4764 - SolrClient::setResponseWriter example
  • Example#4765 - SolrParams::setParam example
  • Example#4766 - SolrQuery::addFacetField example
  • Example#4767 - SolrQuery::addFacetField example
  • Example#4768 - SolrQuery::addFilterQuery example
  • Example#4769 - SolrQuery::addGroupSortField example
  • Example#4770 - SolrQuery::collapse example
  • Example#4771 - SolrQuery::setExpand example
  • Example#4772 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4773 - SolrDisMaxQuery::addBoostQuery example
  • Example#4774 - SolrDisMaxQuery::addPhraseField example
  • Example#4775 - SolrDisMaxQuery::addQueryField example
  • Example#4776 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4777 - SolrDisMaxQuery::addUserField example
  • Example#4778 - SolrDisMaxQuery::__construct example
  • Example#4779 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4780 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4781 - SolrDisMaxQuery::removePhraseField example
  • Example#4782 - SolrDisMaxQuery::removeQueryField example
  • Example#4783 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4784 - SolrDisMaxQuery::removeUserField example
  • Example#4785 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4786 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4787 - SolrDisMaxQuery::setBoostFunction example
  • Example#4788 - SolrDisMaxQuery::setBoostQuery example
  • Example#4789 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4790 - SolrDisMaxQuery::setPhraseFields example
  • Example#4791 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4792 - SolrDisMaxQuery::setQueryAlt example
  • Example#4793 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4794 - SolrDisMaxQuery::setTieBreaker example
  • Example#4795 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4796 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4797 - SolrDisMaxQuery::setUserFields example
  • Example#4798 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4799 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4800 - SolrCollapseFunction::__construct example
  • Example#4801 - SolrCollapseFunction::setHint example
  • Example#4802 - SolrCollapseFunction::setMax example
  • Example#4803 - Turning off PHP parsing for a directory using .htaccess
  • Example#4804 - apache_get_modules example
  • Example#4805 - apache_get_version example
  • Example#4806 - apache_getenv example
  • Example#4807 - apache_lookup_uri example
  • Example#4808 - Passing information between PHP and Perl
  • Example#4809 - Logging values in access.log
  • Example#4810 - apache_request_headers example
  • Example#4811 - apache_response_headers example
  • Example#4812 - Setting an Apache environment variable using apache_setenv
  • Example#4813 - getallheaders example
  • Example#4814 - Registering a variable with $_SESSION.
  • Example#4815 - Unregistering a variable with $_SESSION.
  • Example#4816 - Counting the number of hits of a single user
  • Example#4817 - Example information
  • Example#4818 - session_cache_expire example
  • Example#4819 - session_cache_limiter example
  • Example#4820 - session_create_id example with session_regenerate_id
  • Example#4821 - Destroying a session with $_SESSION
  • Example#4822 - session_gc example for task managers like cron
  • Example#4823 - session_gc example for user accessible script
  • Example#4824 - session_name example
  • Example#4825 - A session_regenerate_id example
  • Example#4826 - Avoiding lost session by session_regenerate_id
  • Example#4827 - Custom session handler: see full code in SessionHandlerInterface synopsis.
  • Example#4828 - page1.php
  • Example#4829 - page2.php
  • Example#4830 - Overriding the cookie lifetime
  • Example#4831 - Reading the session and closing it
  • Example#4832 - Using SessionHandler to add encryption to internal PHP save handlers.
  • Example#4833 - Example using SessionHandlerInterface
  • Example#4834 - Tokenize comma separated integer list
  • Example#4835 - Tokenize assign statement
  • Example#4836 - Simple calculator
  • Example#4837 - Parse words out from a sentence
  • Example#4838 - Examples of valid patterns
  • Example#4839 - Examples of invalid patterns
  • Example#4840 - Usage of comments in PCRE pattern
  • Example#4841 - Example comparing preg_filter with preg_replace
  • Example#4842 - preg_grep example
  • Example#4843 - preg_last_error_msg example
  • Example#4844 - preg_last_error example
  • Example#4845 - Getting all phone numbers out of some text.
  • Example#4846 - Find matching HTML tags (greedy)
  • Example#4847 - Using named subpattern
  • Example#4848 - Find the string of text "php"
  • Example#4849 - Find the word "web"
  • Example#4850 - Getting the domain name out of a URL
  • Example#4851 - Using named subpattern
  • Example#4852 - preg_quote example
  • Example#4853 - Italicizing a word within some text
  • Example#4854 - preg_replace_callback_array example
  • Example#4855 - preg_replace_callback and anonymous function
  • Example#4856 - preg_replace_callback example
  • Example#4857 - preg_replace_callback using recursive structure to handle encapsulated BB code
  • Example#4858 - Using backreferences followed by numeric literals
  • Example#4859 - Using indexed arrays with preg_replace
  • Example#4860 - Replacing several values
  • Example#4861 - Strip whitespace
  • Example#4862 - Using the count parameter
  • Example#4863 -
  • Example#4864 - preg_split example : Get the parts of a search string
  • Example#4865 - Splitting a string into component characters
  • Example#4866 - Splitting a string into matches and their offsets
  • Example#4867 - addcslashes example
  • Example#4868 - An addslashes example
  • Example#4869 - bin2hex example
  • Example#4870 - chr example
  • Example#4871 - Overflow behavior
  • Example#4872 - Building a UTF-8 string from individual bytes
  • Example#4873 - chunk_split example
  • Example#4874 - convert_uudecode example
  • Example#4875 - convert_uuencode example
  • Example#4876 - count_chars example
  • Example#4877 - Displaying a crc32 checksum
  • Example#4878 - crypt examples
  • Example#4879 - echo examples
  • Example#4880 -
  • Example#4881 - explode examples
  • Example#4882 - explode return examples
  • Example#4883 - limit parameter examples
  • Example#4884 - fprintf: zero-padded integers
  • Example#4885 - fprintf: formatting currency
  • Example#4886 - Translation Table Example
  • Example#4887 - hex2bin example
  • Example#4888 - Decoding HTML entities
  • Example#4889 - A htmlentities example
  • Example#4890 - Usage of ENT_IGNORE
  • Example#4891 - A htmlspecialchars_decode example
  • Example#4892 - htmlspecialchars example
  • Example#4893 - implode example
  • Example#4894 - lcfirst example
  • Example#4895 - levenshtein example
  • Example#4896 - localeconv example
  • Example#4897 - Usage example of ltrim
  • Example#4898 - Usage example of md5_file
  • Example#4899 - A md5 example
  • Example#4900 - metaphone basic example
  • Example#4901 - Using the max_phonemes parameter
  • Example#4902 - Using the max_phonemes parameter
  • Example#4903 - money_format Example
  • Example#4904 - nl_langinfo example
  • Example#4905 - Using nl2br
  • Example#4906 - Generating valid HTML markup using the use_xhtml parameter
  • Example#4907 - Various newline separators
  • Example#4908 - number_format Example
  • Example#4909 - ord example
  • Example#4910 - Examining the individual bytes of a UTF-8 string
  • Example#4911 - Using parse_str
  • Example#4912 - parse_str name mangling
  • Example#4913 - print examples
  • Example#4914 -
  • Example#4915 -
  • Example#4916 - printf: various examples
  • Example#4917 - printf: string specifiers
  • Example#4918 - quoted_printable_decode example
  • Example#4919 - quoted_printable_encode example
  • Example#4920 - quotemeta example
  • Example#4921 - Usage example of rtrim
  • Example#4922 - setlocale Examples
  • Example#4923 - setlocale Examples for Windows
  • Example#4924 - sha1_file example
  • Example#4925 - A sha1 example
  • Example#4926 - similar_text argument swapping example
  • Example#4927 - Soundex Examples
  • Example#4928 - Argument swapping
  • Example#4929 - Specifying padding character
  • Example#4930 - Position specifier with other specifiers
  • Example#4931 - sprintf: zero-padded integers
  • Example#4932 - sprintf: formatting currency
  • Example#4933 - sprintf: scientific notation
  • Example#4934 - sscanf Example
  • Example#4935 - sscanf - using optional parameters
  • Example#4936 - Using the empty string ''
  • Example#4937 - Showing case-sensitivity
  • Example#4938 - Basic str_decrement example
  • Example#4939 - str_decrement example with a carry
  • Example#4940 - Using the empty string ''
  • Example#4941 - Showing case-sensitivity
  • Example#4942 - str_getcsv example
  • Example#4943 - str_getcsv example with an empty string
  • Example#4944 - Basic str_increment example
  • Example#4945 - str_increment example with a carry
  • Example#4946 - str_ireplace example
  • Example#4947 - str_pad example
  • Example#4948 - str_repeat example
  • Example#4949 - Basic str_replace examples
  • Example#4950 - Examples of potential str_replace gotchas
  • Example#4951 - str_rot13 example
  • Example#4952 - str_shuffle example
  • Example#4953 - Example uses of str_split
  • Example#4954 - Using the empty string ''
  • Example#4955 - Showing case-sensitivity
  • Example#4956 - A str_word_count example
  • Example#4957 - strcasecmp example
  • Example#4958 - strcmp example
  • Example#4959 - strcspn example
  • Example#4960 - strip_tags example
  • Example#4961 - stripcslashes example
  • Example#4962 - stripos examples
  • Example#4963 - A stripslashes example
  • Example#4964 - Using stripslashes on an array
  • Example#4965 - stristr example
  • Example#4966 - Testing if a string is found or not
  • Example#4967 - Using a non "string" needle
  • Example#4968 - A strlen example
  • Example#4969 - strnatcasecmp example
  • Example#4970 - strncasecmp example
  • Example#4971 - strncmp example
  • Example#4972 - strpbrk example
  • Example#4973 - Using ===
  • Example#4974 - Using !==
  • Example#4975 - Using an offset
  • Example#4976 - strrchr example
  • Example#4977 - Reversing a string with strrev
  • Example#4978 - A simple strripos example
  • Example#4979 - Checking if a needle is in the haystack
  • Example#4980 - Searching with offsets
  • Example#4981 - strspn example
  • Example#4982 - strstr example
  • Example#4983 - strtok example
  • Example#4984 - strtok behavior on empty part found
  • Example#4985 - The difference between strtok and explode
  • Example#4986 - strtolower example
  • Example#4987 - strtoupper example
  • Example#4988 - strtr example
  • Example#4989 - strtr example with two arguments
  • Example#4990 - strtr behavior comparison
  • Example#4991 - A substr_compare example
  • Example#4992 - A substr_count example
  • Example#4993 - Simple substr_replace examples
  • Example#4994 - Using substr_replace to replace multiple strings at once
  • Example#4995 - Using a negative offset
  • Example#4996 - Using a negative length
  • Example#4997 - Basic substr usage
  • Example#4998 - substr casting behaviour
  • Example#4999 -
  • Example#5000 - Invalid Character Range
  • Example#5001 - Usage example of trim
  • Example#5002 - Trimming array values with trim
  • Example#5003 - ucfirst example
  • Example#5004 - ucwords example
  • Example#5005 - ucwords example with custom delimiter
  • Example#5006 - ucwords example with additional delimiters
  • Example#5007 - Basic examples
  • Example#5008 - Basic example
  • Example#5009 - vfprintf: zero-padded integers
  • Example#5010 - vprintf: zero-padded integers
  • Example#5011 - vsprintf: zero-padded integers
  • Example#5012 - wordwrap example
  • Example#5013 - wordwrap example
  • Example#5014 - wordwrap example
  • Example#5015 - array_change_key_case example
  • Example#5016 - array_chunk example
  • Example#5017 - Get the column of first names from a recordset
  • Example#5018 - Get the column of last names from a recordset, indexed by the "id" column
  • Example#5019 - Get the column of usernames from the public "username" property of an object
  • Example#5020 - Get the column of names from the private "name" property of an object using the magic __get method.
  • Example#5021 - A simple array_combine example
  • Example#5022 - array_count_values example
  • Example#5023 - array_diff_assoc example
  • Example#5024 - array_diff_assoc example
  • Example#5025 - array_diff_key example
  • Example#5026 - array_diff_uassoc example
  • Example#5027 - array_diff_ukey example
  • Example#5028 - array_diff example
  • Example#5029 - array_diff example with non-matching types
  • Example#5030 - array_fill_keys example
  • Example#5031 - array_fill example
  • Example#5032 - array_fill example with a negative start index
  • Example#5033 - array_filter example
  • Example#5034 - array_filter without callback
  • Example#5035 - array_filter with mode
  • Example#5036 - array_flip example
  • Example#5037 - array_flip example : collision
  • Example#5038 - array_intersect_assoc example
  • Example#5039 - array_intersect_key example
  • Example#5040 - array_intersect_uassoc example
  • Example#5041 - array_intersect_ukey example
  • Example#5042 - array_intersect example
  • Example#5043 - array_is_list example
  • Example#5044 - array_key_exists example
  • Example#5045 - array_key_exists vs isset
  • Example#5046 - Basic array_key_first Usage
  • Example#5047 - array_keys example
  • Example#5048 - array_map example
  • Example#5049 - array_map using a lambda function
  • Example#5050 - array_map - using more arrays
  • Example#5051 - Performing a zip operation of arrays
  • Example#5052 - null callback with only array
  • Example#5053 - array_map - with string keys
  • Example#5054 - array_map - associative arrays
  • Example#5055 - array_merge_recursive example
  • Example#5056 - array_merge example
  • Example#5057 - Simple array_merge example
  • Example#5058 - array_merge with non-array types
  • Example#5059 - Sorting multiple arrays
  • Example#5060 - Sorting multi-dimensional array
  • Example#5061 - Sorting database results
  • Example#5062 - Case insensitive sorting
  • Example#5063 - array_pad example
  • Example#5064 - array_pop example
  • Example#5065 - array_product examples
  • Example#5066 - array_push example
  • Example#5067 - array_rand example
  • Example#5068 - array_reduce example
  • Example#5069 - array_replace_recursive example
  • Example#5070 - array_replace_recursive and recursive behavior
  • Example#5071 - array_replace example
  • Example#5072 - array_reverse example
  • Example#5073 - array_search example
  • Example#5074 - array_shift example
  • Example#5075 - array_slice examples
  • Example#5076 - array_slice and one-based array
  • Example#5077 - array_slice and array with mixed keys
  • Example#5078 - array_splice examples
  • Example#5079 - Equivalent statements to various array_splice examples
  • Example#5080 - array_sum examples
  • Example#5081 - array_udiff_assoc example
  • Example#5082 - array_udiff_uassoc example
  • Example#5083 - array_udiff example using stdClass Objects
  • Example#5084 - array_udiff example using DateTime Objects
  • Example#5085 - array_uintersect_assoc example
  • Example#5086 - array_uintersect_uassoc example
  • Example#5087 - array_uintersect example
  • Example#5088 - array_unique example
  • Example#5089 - array_unique and types
  • Example#5090 - array_unshift example
  • Example#5091 - Usage with associative arrays
  • Example#5092 - array_values example
  • Example#5093 - array_walk_recursive example
  • Example#5094 - array_walk example
  • Example#5095 - array_walk example using anonymous function
  • Example#5096 - array example
  • Example#5097 - Automatic index with array
  • Example#5098 - 1-based index with array
  • Example#5099 - Accessing an array inside double quotes
  • Example#5100 - arsort example
  • Example#5101 - asort example
  • Example#5102 - compact example
  • Example#5103 - count example
  • Example#5104 - count non Countable|array example (bad example - don't do this)
  • Example#5105 - Recursive count example
  • Example#5106 - Countable object
  • Example#5107 - Example use of current and friends
  • Example#5108 - each examples
  • Example#5109 - Traversing an array with each
  • Example#5110 - end example
  • Example#5111 - extract example
  • Example#5112 - in_array example
  • Example#5113 - in_array with strict example
  • Example#5114 - in_array with an array as needle
  • Example#5115 - key example
  • Example#5116 - krsort example
  • Example#5117 - ksort example
  • Example#5118 - ksort with int keys
  • Example#5119 - list examples
  • Example#5120 - An example use of list
  • Example#5121 - Using nested list
  • Example#5122 - list and order of index definitions
  • Example#5123 - list with keys
  • Example#5124 - natcasesort example
  • Example#5125 - natsort examples demonstrating basic usage
  • Example#5126 - natsort examples demonstrating potential gotchas
  • Example#5127 - Example use of next and friends
  • Example#5128 - Example use of prev and friends
  • Example#5129 - range examples
  • Example#5130 - reset example
  • Example#5131 - rsort example
  • Example#5132 - shuffle example
  • Example#5133 - sort example
  • Example#5134 - sort example using case-insensitive natural ordering
  • Example#5135 - Basic uasort example
  • Example#5136 - uksort example
  • Example#5137 - usort example
  • Example#5138 - usort example using multi-dimensional array
  • Example#5139 - usort example using a member function of an object
  • Example#5140 - usort example using a closure to sort a multi-dimensional array
  • Example#5141 - usort example using the spaceship operator
  • Example#5142 - Class Definitions
  • Example#5143 - test_script.php
  • Example#5144 - class_alias example
  • Example#5145 - class_exists example
  • Example#5146 - autoload parameter example
  • Example#5147 - enum_exists example
  • Example#5148 - Using get_called_class
  • Example#5149 - get_class_methods example
  • Example#5150 - get_class_vars example
  • Example#5151 - get_class_vars and scoping behaviour
  • Example#5152 - Using get_class
  • Example#5153 - Using get_class in superclass
  • Example#5154 - Using get_class with namespaced classes
  • Example#5155 - get_declared_classes example
  • Example#5156 - get_declared_interfaces example
  • Example#5157 - get_mangled_object_vars example
  • Example#5158 - Use of get_object_vars
  • Example#5159 - Using get_parent_class
  • Example#5160 - interface_exists example
  • Example#5161 - is_a example
  • Example#5162 - Using the instanceof operator
  • Example#5163 - is_subclass_of example
  • Example#5164 - is_subclass_of using interface example
  • Example#5165 - method_exists example
  • Example#5166 - Static method_exists example
  • Example#5167 - A property_exists example
  • Example#5168 - A ctype_alnum example (using the default locale)
  • Example#5169 - A ctype_alpha example (using the default locale)
  • Example#5170 - A ctype_cntrl example
  • Example#5171 - A ctype_digit example
  • Example#5172 - A ctype_digit example comparing strings with integers
  • Example#5173 - A ctype_graph example
  • Example#5174 - A ctype_lower example (using the default locale)
  • Example#5175 - A ctype_print example
  • Example#5176 - A ctype_punct example
  • Example#5177 - A ctype_space example
  • Example#5178 - A ctype_upper example (using the default locale)
  • Example#5179 - A ctype_xdigit example
  • Example#5180 - Configuring the default filter to act like htmlspecialchars
  • Example#5181 - Configuring the default filter to act like htmlspecialchars
  • Example#5182 - Validating email addresses with filter_var
  • Example#5183 - Validating IP addresses with filter_var
  • Example#5184 - Passing options to filter_var
  • Example#5185 - Sanitizing and validating email addresses
  • Example#5186 - Configuring a default filter
  • Example#5187 - A filter_input_array example
  • Example#5188 - A filter_input example
  • Example#5189 - A filter_list example
  • Example#5190 - A filter_var_array example
  • Example#5191 - A filter_var example
  • Example#5192 - Filter an array example
  • Example#5193 - call_user_func_array example
  • Example#5194 - call_user_func_array using namespace name
  • Example#5195 - Using lambda function
  • Example#5196 - Passing values by reference
  • Example#5197 - call_user_func_array using named arguments
  • Example#5198 - call_user_func example and references
  • Example#5199 - call_user_func example
  • Example#5200 - call_user_func using namespace name
  • Example#5201 - Using a class method with call_user_func
  • Example#5202 - Using lambda function with call_user_func
  • Example#5203 - Creating a function dynamically, with create_function or anonymous functions
  • Example#5204 - Making a general processing function, with create_function or anonymous functions
  • Example#5205 - Using dynamic functions as callback functions
  • Example#5206 - forward_static_call_array example
  • Example#5207 - forward_static_call example
  • Example#5208 - func_get_arg example
  • Example#5209 - func_get_arg example of byref and byval arguments
  • Example#5210 - func_get_args example
  • Example#5211 - func_get_args example of byref and byval arguments
  • Example#5212 - func_num_args example
  • Example#5213 - function_exists example
  • Example#5214 - get_defined_functions example
  • Example#5215 - register_shutdown_function example
  • Example#5216 - register_tick_function example
  • Example#5217 - Quickhash Example
  • Example#5218 - Quickhash ArrayAccess Example
  • Example#5219 - Quickhash Iterator Example
  • Example#5220 - Quickhash String Values Example
  • Example#5221 - QuickHashIntSet::add example
  • Example#5222 - QuickHashIntSet::__construct example
  • Example#5223 - QuickHashIntSet::delete example
  • Example#5224 - QuickHashIntSet::exists example
  • Example#5225 - QuickHashIntSet::getSize example
  • Example#5226 - QuickHashIntSet::loadFromFile example
  • Example#5227 - QuickHashIntSet::loadFromString example
  • Example#5228 - QuickHashIntSet::saveToFile example
  • Example#5229 - QuickHashIntSet::saveToString example
  • Example#5230 - QuickHashIntHash::add example
  • Example#5231 - QuickHashIntHash::__construct example
  • Example#5232 - QuickHashIntHash::delete example
  • Example#5233 - QuickHashIntHash::exists example
  • Example#5234 - QuickHashIntHash::get example
  • Example#5235 - QuickHashIntHash::getSize example
  • Example#5236 - QuickHash IntHash file format
  • Example#5237 - QuickHash IntHash file format
  • Example#5238 - QuickHashIntHash::loadFromFile example
  • Example#5239 - QuickHashIntHash::loadFromString example
  • Example#5240 - QuickHashIntHash::saveToFile example
  • Example#5241 - QuickHashIntHash::saveToString example
  • Example#5242 - QuickHashIntHash::set example
  • Example#5243 - QuickHashIntHash::update example
  • Example#5244 - QuickHashStringIntHash::add example
  • Example#5245 - QuickHashStringIntHash::__construct example
  • Example#5246 - QuickHashStringIntHash::delete example
  • Example#5247 - QuickHashStringIntHash::get example
  • Example#5248 - QuickHashStringIntHash::getSize example
  • Example#5249 - QuickHash StringIntHash file format
  • Example#5250 - QuickHash IntHash file format
  • Example#5251 - QuickHashStringIntHash::loadFromFile example
  • Example#5252 - QuickHashStringIntHash::loadFromString example
  • Example#5253 - QuickHashStringIntHash::saveToFile example
  • Example#5254 - QuickHashStringIntHash::saveToString example
  • Example#5255 - QuickHashStringIntHash::set example
  • Example#5256 - QuickHashStringIntHash::update example
  • Example#5257 - QuickHashIntStringHash::add example
  • Example#5258 - QuickHashIntStringHash::__construct example
  • Example#5259 - QuickHashIntStringHash::delete example
  • Example#5260 - QuickHashIntStringHash::get example
  • Example#5261 - QuickHashIntStringHash::getSize example
  • Example#5262 - QuickHash IntString file format
  • Example#5263 - QuickHash IntString file format
  • Example#5264 - QuickHashIntStringHash::loadFromFile example
  • Example#5265 - QuickHashIntStringHash::loadFromString example
  • Example#5266 - QuickHashIntStringHash::saveToFile example
  • Example#5267 - QuickHashIntStringHash::saveToString example
  • Example#5268 - QuickHashIntStringHash::set example
  • Example#5269 - QuickHashIntStringHash::update example
  • Example#5270 - Reflection Example from Shell (a Terminal)
  • Example#5271 - Extending the built-in classes
  • Example#5272 - Reflection::getModifierNames example
  • Example#5273 - Basic usage ReflectionClass
  • Example#5274 - Basic usage of ReflectionClass::export
  • Example#5275 - Basic usage
  • Example#5276 - Filtering results by class name
  • Example#5277 - Filtering results by class name, with inheritance
  • Example#5278 - Usage of ReflectionClass::getConstant
  • Example#5279 - Basic usage of ReflectionClass::getConstructor
  • Example#5280 - ReflectionClass::getDefaultProperties example
  • Example#5281 - ReflectionClass::getDocComment example
  • Example#5282 - ReflectionClass::getEndLine example
  • Example#5283 - Basic usage of ReflectionClass::getExtension
  • Example#5284 - Basic usage of ReflectionClass::getExtensionName
  • Example#5285 - ReflectionClass::getInterfaceNames example
  • Example#5286 - ReflectionClass::getInterfaces example
  • Example#5287 - Basic usage of ReflectionClass::getMethod
  • Example#5288 - Basic usage of ReflectionClass::getMethods
  • Example#5289 - Filtering results from ReflectionClass::getMethods
  • Example#5290 - ReflectionClass::getName example
  • Example#5291 - ReflectionClass::getNamespaceName example
  • Example#5292 - ReflectionClass::getProperties filtering example
  • Example#5293 - Basic usage of ReflectionClass::getProperty
  • Example#5294 - Basic ReflectionClass::getReflectionConstants example
  • Example#5295 - ReflectionClass::getShortName example
  • Example#5296 - Basic usage of ReflectionClass::getStaticPropertyValue
  • Example#5297 - ReflectionClass::hasConstant example
  • Example#5298 - ReflectionClass::hasMethod example
  • Example#5299 - ReflectionClass::hasProperty example
  • Example#5300 - ReflectionClass::inNamespace example
  • Example#5301 - ReflectionClass::isAbstract example
  • Example#5302 - ReflectionClass::isAnonymous example
  • Example#5303 - Basic usage of ReflectionClass::isCloneable
  • Example#5304 - ReflectionClass::isFinal example
  • Example#5305 - ReflectionClass::isInstance related examples
  • Example#5306 - ReflectionClass::isInstantiable example
  • Example#5307 - Basic usage of ReflectionClass::isInterface
  • Example#5308 - Basic usage of ReflectionClass::isInternal
  • Example#5309 - Basic ReflectionClass::isIterable Usage
  • Example#5310 - ReflectionClass::isReadOnly example
  • Example#5311 - Basic usage of ReflectionClass::newInstanceArgs
  • Example#5312 - ReflectionClass::__toString example
  • Example#5313 - Basic usage
  • Example#5314 - Filtering results by class name
  • Example#5315 - Filtering results by class name, with inheritance
  • Example#5316 - ReflectionClassConstant::isEnumCase example
  • Example#5317 - ReflectionEnum::getBackingType example
  • Example#5318 - ReflectionEnum::getCase example
  • Example#5319 - ReflectionEnum::getCases example
  • Example#5320 - ReflectionEnum::hasCase example
  • Example#5321 - ReflectionEnum::isBacked example
  • Example#5322 - ReflectionEnum::getValue example
  • Example#5323 - ReflectionEnum::getBackingValue example
  • Example#5324 - ReflectionExtension example
  • Example#5325 - ReflectionExtension::getClasses example
  • Example#5326 - ReflectionExtension::getClassNames example
  • Example#5327 - ReflectionExtension::getConstants example
  • Example#5328 - ReflectionExtension::getDependencies example
  • Example#5329 - ReflectionExtension::getFunctions example
  • Example#5330 - ReflectionExtension::getINIEntries example
  • Example#5331 - ReflectionExtension::getName example
  • Example#5332 - ReflectionExtension::getVersion example
  • Example#5333 - ReflectionExtension::info example
  • Example#5334 - ReflectionFunction::__construct example
  • Example#5335 - ReflectionFunction::invoke example
  • Example#5336 - ReflectionFunction::invokeArgs example
  • Example#5337 - ReflectionFunction::invokeArgs with references example
  • Example#5338 - ReflectionFunction::isAnonymous example
  • Example#5339 - ReflectionFunction::__toString example
  • Example#5340 - Basic usage with a class method
  • Example#5341 - Basic usage with a function
  • Example#5342 - Filtering results by class name
  • Example#5343 - Filtering results by class name, with inheritance
  • Example#5344 - ReflectionFunctionAbstract::getClosureUsedVariables example
  • Example#5345 - ReflectionFunctionAbstract::getReturnType example
  • Example#5346 - Usage on built-in functions
  • Example#5347 - ReflectionFunctionAbstract::getTentativeReturnType example
  • Example#5348 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5349 - Usage on built-in functions
  • Example#5350 - ReflectionFunctionAbstract::hasTentativeReturnType example
  • Example#5351 - ReflectionFunctionAbstract::isClosure example
  • Example#5352 - ReflectionFunctionAbstract::isDeprecated example
  • Example#5353 - ReflectionMethod::__construct example
  • Example#5354 - ReflectionMethod::createFromMethodName example
  • Example#5355 - ReflectionMethod::getDeclaringClass example
  • Example#5356 - ReflectionMethod::getModifiers example
  • Example#5357 - ReflectionMethod::getPrototype example
  • Example#5358 - ReflectionMethod::hasPrototype example
  • Example#5359 - ReflectionMethod::invoke example
  • Example#5360 - ReflectionMethod::invokeArgs example
  • Example#5361 - Simple Class definition
  • Example#5362 - ReflectionMethod::__toString example
  • Example#5363 - ReflectionNamedType::isBuiltin example
  • Example#5364 - Using the ReflectionParameter class
  • Example#5365 - Basic usage
  • Example#5366 - Filtering results by class name
  • Example#5367 - Filtering results by class name, with inheritance
  • Example#5368 - Using the ReflectionParameter class
  • Example#5369 - Getting the class that declared the method
  • Example#5370 - Getting default values of function parameters
  • Example#5371 - Getting default values' constant names of function parameters
  • Example#5372 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5373 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5374 - ReflectionParameter::getType Usage in PHP 8.0.0 and later
  • Example#5375 - ReflectionParameter::hasType example
  • Example#5376 - PHP 8.0.0 equivalent
  • Example#5377 - PHP 8.0.0 equivalent
  • Example#5378 - ReflectionParameter::__toString example
  • Example#5379 - ReflectionProperty::__construct example
  • Example#5380 - Getting value from private and protected properties using ReflectionProperty class
  • Example#5381 - Basic usage
  • Example#5382 - Filtering results by class name
  • Example#5383 - Filtering results by class name, with inheritance
  • Example#5384 - ReflectionProperty::getDefaultValue example
  • Example#5385 - ReflectionProperty::getDocComment example
  • Example#5386 - Multiple property declarations
  • Example#5387 - ReflectionProperty::getType example
  • Example#5388 - ReflectionProperty::getValue example
  • Example#5389 - ReflectionProperty::hasDefaultValue example
  • Example#5390 - ReflectionProperty::hasType example
  • Example#5391 - ReflectionProperty::isDefault example
  • Example#5392 - ReflectionProperty::isInitialized example
  • Example#5393 - ReflectionProperty::isPromoted example
  • Example#5394 - Simple Class definition
  • Example#5395 - ReflectionProperty::setValue example
  • Example#5396 - ReflectionType::allowsNull example
  • Example#5397 - ReflectionType::__toString example
  • Example#5398 - ReflectionUnionType::getTypes example
  • Example#5399 - ReflectionGenerator::__construct example
  • Example#5400 - ReflectionGenerator::getExecutingFile example
  • Example#5401 - ReflectionGenerator::getExecutingGenerator example
  • Example#5402 - ReflectionGenerator::getExecutingLine example
  • Example#5403 - ReflectionGenerator::getFunction example
  • Example#5404 - ReflectionGenerator::getThis example
  • Example#5405 - ReflectionGenerator::getTrace example
  • Example#5406 - ReflectionIntersectionType::getTypes example
  • Example#5407 - Basic ReflectionReference::getId usage
  • Example#5408 - boolval examples
  • Example#5409 - debug_zval_dump example
  • Example#5410 -
  • Example#5411 - A simple empty / isset comparison.
  • Example#5412 - empty on String Offsets
  • Example#5413 - floatval Example
  • Example#5414 - floatval non-numeric leftmost characters Example
  • Example#5415 - get_debug_type example
  • Example#5416 - get_defined_vars Example
  • Example#5417 - get_resource_id produces the same result as an int cast
  • Example#5418 - get_resource_type example
  • Example#5419 - gettype example
  • Example#5420 - intval examples
  • Example#5421 - Check that variable is an array
  • Example#5422 - is_bool examples
  • Example#5423 - is_callable example
  • Example#5424 - is_callable and constructors
  • Example#5425 - is_countable examples
  • Example#5426 - is_float example
  • Example#5427 - is_int example
  • Example#5428 - is_iterable examples
  • Example#5429 - is_null example
  • Example#5430 - is_numeric examples
  • Example#5431 - is_numeric with whitespace
  • Example#5432 - is_object example
  • Example#5433 - is_resource example
  • Example#5434 - is_scalar example
  • Example#5435 - is_string example
  • Example#5436 - isset Examples
  • Example#5437 - isset on String Offsets
  • Example#5438 - print_r example
  • Example#5439 - return parameter example
  • Example#5440 - serialize example
  • Example#5441 - settype example
  • Example#5442 - strval example using PHP magic __toString() method.
  • Example#5443 - unserialize example
  • Example#5444 - unserialize_callback_func example
  • Example#5445 - unset example
  • Example#5446 - Using (unset) casting
  • Example#5447 - var_dump example
  • Example#5448 - var_export Examples
  • Example#5449 - Exporting stdClass (since PHP 7.3.0)
  • Example#5450 - Exporting classes
  • Example#5451 - Using __set_state()
  • Example#5452 -
  • Example#5453 - OAuth::fetch example
  • Example#5454 - OAuth::getAccessToken example
  • Example#5455 - OAuth::getRequestToken example
  • Example#5456 - OAuth::setRequestEngine example
  • Example#5457 - An OAuth::setRsaCertificate example
  • Example#5458 - OAuth::setToken example
  • Example#5459 - OAuthProvider::__construct example
  • Example#5460 - Example OAuthProvider::consumerHandler callback
  • Example#5461 - OAuthProvider::generateToken example
  • Example#5462 - OAuthProvider::is2LeggedEndpoint example
  • Example#5463 - Example OAuthProvider::timestampNonceHandler callback
  • Example#5464 - Example OAuthProvider::tokenHandler callback
  • Example#5465 - is_soap_fault example
  • Example#5466 - SOAP's standard method for error reporting is exceptions
  • Example#5467 - Specifying use of TLS 1.3 only
  • Example#5468 - SoapClient::__construct example
  • Example#5469 - Using the SOAP_SINGLE_ELEMENT_ARRAYS feature
  • Example#5470 - SoapClient::__doRequest example
  • Example#5471 - SoapClient::__getFunctions example
  • Example#5472 - SoapClient::__getLastRequest() example
  • Example#5473 - SoapClient::__getLastRequestHeaders() example
  • Example#5474 - SoapClient::__getLastResponse() example
  • Example#5475 - SoapClient::__getLastResponse() example
  • Example#5476 - SoapClient::__getTypes example
  • Example#5477 - SoapClient::__setLocation example
  • Example#5478 - SoapClient::__setSoapHeaders example
  • Example#5479 - Set Multiple Headers
  • Example#5480 - SoapClient::__soapCall example
  • Example#5481 - SoapServer::addFunction example
  • Example#5482 - SoapServer::__construct example
  • Example#5483 - SoapServer::getFunctions example
  • Example#5484 - SoapServer::handle example
  • Example#5485 - SoapServer::setPersistence example
  • Example#5486 - Some examples
  • Example#5487 - Some examples
  • Example#5488 - SoapHeader::__construct example
  • Example#5489 - SoapParam::__construct example
  • Example#5490 - SoapVar::__construct example
  • Example#5491 - Yar Server Example
  • Example#5492 - Access the server in borwser(GET request)
  • Example#5493 - Yar Client Example
  • Example#5494 - Yar Concurrent Client Example
  • Example#5495 - Yar_Server::__construct example
  • Example#5496 - Yar_Server::handle example
  • Example#5497 - Yar_Client::__call example
  • Example#5498 - Yar_Client::__construct example
  • Example#5499 - Yar_Client::setOpt example
  • Example#5500 - Yar_Concurrent_Client::call example
  • Example#5501 - Yar_Concurrent_Client::loop example
  • Example#5502 - Yar_Concurrent_Client::reset example
  • Example#5503 - Yar_Server_Exception::getType example
  • Example#5504 - Yar_Client_Exception::getType example
  • Example#5505 - XMLRPC client functions example
  • Example#5506 - XML-RPC type example
  • Example#5507 - A xmlrpc_set_type example
  • Example#5508 - For Each in ASP
  • Example#5509 - foreach in PHP
  • Example#5510 - com example (1)
  • Example#5511 - com example (2)
  • Example#5512 - dotnet example
  • Example#5513 - variant example
  • Example#5514 - Basic COMPersistHelper::saveToFile Usage
  • Example#5515 - COM event sink example
  • Example#5516 - Registering a PHP script to run as a service
  • Example#5517 - Unregistering a service
  • Example#5518 - Running as a service
  • Example#5519 - A win32_create_service example
  • Example#5520 - A win32_create_service example with dependencies
  • Example#5521 - A win32_create_service example with recovery
  • Example#5522 - A win32_delete_service example
  • Example#5523 - A win32_start_service_ctrl_dispatcher example
  • Example#5524 - book.xml
  • Example#5525 - Creating a new DOMAttr object
  • Example#5526 - DOMAttr::isId() Example
  • Example#5527 - Creating a new DOMCdataSection object
  • Example#5528 - DOMCharacterData::after example
  • Example#5529 - DOMCharacterData::before example
  • Example#5530 - DOMCharacterData::remove example
  • Example#5531 - DOMCharacterData::replaceWith example
  • Example#5532 - Creating a new DOMComment
  • Example#5533 - DOMDocument::adoptNode example
  • Example#5534 - DOMDocument::append example
  • Example#5535 - Creating a new DOMDocument
  • Example#5536 - Creating a new element and inserting it as root
  • Example#5537 - Passing text containing an unescaped & as value
  • Example#5538 - Creating a new element and inserting it as root
  • Example#5539 - A namespace prefix example
  • Example#5540 - DOMDocument::getElementById() Example
  • Example#5541 - Basic Usage Example
  • Example#5542 - Get all the XInclude elements
  • Example#5543 - DOMDocument::importNode example
  • Example#5544 - Creating a Document
  • Example#5545 - Creating a Document
  • Example#5546 - Creating a Document
  • Example#5547 - Creating a Document
  • Example#5548 - DOMDocument::prepend example
  • Example#5549 - Adding a new method to DOMElement to ease our code
  • Example#5550 - Retrieving elements as custom class
  • Example#5551 - Retrieving owner document
  • Example#5552 - Custom objects are transient
  • Example#5553 - DOMDocument::replaceChildren example
  • Example#5554 - Saving a DOM tree into a file
  • Example#5555 - Saving a HTML tree into a string
  • Example#5556 - Saving a HTML tree into a file
  • Example#5557 - Saving a DOM tree into a string
  • Example#5558 - Example of DTD validation
  • Example#5559 - DOMDocument::xinclude() example
  • Example#5560 - DOMDocumentFragment::append example
  • Example#5561 - Appending XML data to your document
  • Example#5562 - DOMDocumentFragment::prepend example
  • Example#5563 - DOMDocumentFragment::replaceChildren example
  • Example#5564 - DOMElement::after example
  • Example#5565 - DOMElement::append example
  • Example#5566 - DOMElement::before example
  • Example#5567 - Creating a new DOMElement
  • Example#5568 - DOMElement::getAttributeNames example
  • Example#5569 - DOMElement::insertAdjacentElement example
  • Example#5570 - DOMElement::insertAdjacentText example
  • Example#5571 - DOMElement::prepend example
  • Example#5572 - DOMElement::remove example
  • Example#5573 - DOMElement::replaceChildren example
  • Example#5574 - DOMElement::replaceWith example
  • Example#5575 - Setting an attribute
  • Example#5576 - DOMElement::toggleAttribute example
  • Example#5577 - Creating a new DOMEntityReference
  • Example#5578 - Creating a document with an attached DTD
  • Example#5579 - Testing your DOM Implementation
  • Example#5580 - Adding a child
  • Example#5581 - Nested children
  • Example#5582 - DOMNode::contains example
  • Example#5583 - DOMNode::getLineNo example
  • Example#5584 - DOMNode::getNodePath example
  • Example#5585 - DOMNode::getRootNode example
  • Example#5586 - DOMNode::isEqualNode example
  • Example#5587 - Removing a child
  • Example#5588 - Traversing all the entries of the table
  • Example#5589 - DOMParentNode::replaceChildren example
  • Example#5590 - Creating a new DOMProcessingInstruction object
  • Example#5591 - Creating a new DOMText
  • Example#5592 - Getting the count of all the english books
  • Example#5593 - Getting all the english books
  • Example#5594 - book.xml
  • Example#5595 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#5596 - DOMXPath::registerPHPFunctions with php:function
  • Example#5597 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#5598 - A libxml_get_errors example
  • Example#5599 - libxml_set_external_entity_loader example
  • Example#5600 - A libxml_set_streams_context example
  • Example#5601 - A libxml_use_internal_errors example
  • Example#5602 - Include file example.php with XML string
  • Example#5603 - Getting <plot>
  • Example#5604 - Getting <line>
  • Example#5605 - Accessing non-unique elements in SimpleXML
  • Example#5606 - Using attributes
  • Example#5607 - Comparing Elements and Attributes with Text
  • Example#5608 - Comparing Two Elements
  • Example#5609 - Using XPath
  • Example#5610 - Setting values
  • Example#5611 - Adding elements and attributes
  • Example#5612 - DOM Interoperability
  • Example#5613 - Loading broken XML string
  • Example#5614 - Add attributes and children to a SimpleXML element
  • Example#5615 - Add attributes and children to a SimpleXML element
  • Example#5616 - Get XML
  • Example#5617 - Using asXML() on SimpleXMLElement::xpath results
  • Example#5618 - Interpret an XML string
  • Example#5619 - Traversing a children() pseudo-array
  • Example#5620 - Using namespaces
  • Example#5621 - Create a SimpleXMLElement object
  • Example#5622 - Create a SimpleXMLElement object from a URL
  • Example#5623 - Counting the number of children
  • Example#5624 - Return the current element
  • Example#5625 - Get document namespaces
  • Example#5626 - Working with multiple namespaces
  • Example#5627 - Get XML element names
  • Example#5628 - Get document namespaces in use
  • Example#5629 - Return the sub-elements of the current element
  • Example#5630 - Check whether the current element has sub-elements
  • Example#5631 - Get the current XML tag key
  • Example#5632 - Move to the next element
  • Example#5633 - Setting a namespace prefix to use in an XPath query
  • Example#5634 - Rewind to the first element
  • Example#5635 - Get string content
  • Example#5636 - Check whether the current element is valid
  • Example#5637 - Xpath
  • Example#5638 - Importing DOM
  • Example#5639 - Interpret an XML document
  • Example#5640 - Interpret an XML string
  • Example#5641 - Serializing a single value with WDDX
  • Example#5642 - Using incremental packets with WDDX
  • Example#5643 - wddx_serialize_vars example
  • Example#5644 - Show XML Element Structure
  • Example#5645 - Map XML to HTML
  • Example#5646 - External Entity Example
  • Example#5647 - xmltest.xml
  • Example#5648 - xmltest2.xml
  • Example#5649 - xml_parse_into_struct example
  • Example#5650 - moldb.xml - small database of molecular information
  • Example#5651 - parsemoldb.php - parses moldb.xml into an array of molecular objects
  • Example#5652 - Chunked parsing of large XML documents
  • Example#5653 - xml_set_object example
  • Example#5654 - Validating XML
  • Example#5655 - Creating a simple XML document
  • Example#5656 - Working with XML namespaces
  • Example#5657 - Working with the OO API
  • Example#5658 - Direct output of XML
  • Example#5659 - XMLWriter::setIndent and mixed Content
  • Example#5660 - Basic XMLWriter::startAttribute Usage
  • Example#5661 - Intermixing Sub-elements and Attributes
  • Example#5662 - Basic xmlwriter_write_cdata Usage
  • Example#5663 - collection.xml
  • Example#5664 - collection.xsl
  • Example#5665 - fruits.xml
  • Example#5666 - fruits.xsl
  • Example#5667 - Collating and printing errors
  • Example#5668 - Creating an XSLTProcessor
  • Example#5669 - Testing EXSLT support
  • Example#5670 - Simple PHP Function call from a stylesheet
  • Example#5671 - Changing the owner before the transformation
  • Example#5672 - Example profiling output
  • Example#5673 - Transforming to a DOMDocument
  • Example#5674 - Transforming to a HTML file
  • Example#5675 - Transforming to a string
  • Example#5676 - A hidden HTML form element
  • Example#5677 - Data to be edited by the user
  • Example#5678 - In a URL
  • Example#5679 - Generating Javascript with PHP
  • Example#5680 - Example PHP/FI Code
  • Example#5681 - Activate full on-screen error reporting for dev. domain
  • Example#5682 - Add security script for protected areas
  • Example#5683 - Unix include_path
  • Example#5684 - Windows include_path
  • Example#5685 - Unix include_path using ${USER} env variable
  • Example#5686 - string.rot13
  • Example#5687 - string.toupper
  • Example#5688 - string.tolower
  • Example#5689 - string.strip_tags
  • Example#5690 - convert.base64-encode & convert.base64-decode
  • Example#5691 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5692 - convert.iconv.*
  • Example#5693 - zlib.deflate and zlib.inflate
  • Example#5694 - zlib.deflate simple
  • Example#5695 - bzip2.compress and bzip2.decompress
  • Example#5696 - Encrypt/Decrypt with Blowfish
  • Example#5697 - Encrypt file using AES-128 CBC with SHA256 HMAC

User Contributed Notes

There are no user contributed notes for this page.


Changelog

The following changes have been made to functions of bundled extensions.

Version Function Description

User Contributed Notes

There are no user contributed notes for this page.


HTML Help Edition

  • About This Edition
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Integrating the PHP Manual

User Contributed Notes

There are no user contributed notes for this page.


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.

User Contributed Notes

There are no user contributed notes for this page.


Using PHP Manual CHM Edition

Table of Contents

  • 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

Table of Contents

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Note:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

User Contributed Notes

There are no user contributed notes for this page.


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Note:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

User Contributed Notes

There are no user contributed notes for this page.


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Note:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.

User Contributed Notes

There are no user contributed notes for this page.


Integrating the PHP Manual

Note:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Note:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.

User Contributed Notes

There are no user contributed notes for this page.