XML
Empty
$childNodes Property
Objects of the DOMDocument, DOMNode,
DOMProcessingInstruction, DOMComment,
DOMText, DOMCdataSection, and
DOMNotation classes have a $childNodes
property. According to the DOM Level 2 Core, DOM Level 3 Core, and
the DOM Living Standard standards, $childNodes must
always be an object of DOMNodeList. Even if there are
no child nodes, in which case the DOMNodeList object
should be empty, of course. Due to a bug, however,
$childNodes was wrongly set to null when
there are no child nodes. This bug has been fixed in PHP 7.3.16 and
PHP 7.4.4.
For an example, let us have a look at
DOMImplementation:
$dom = new DOMImplementation;
$type = $dom->createDocumentType('html');
var_dump($type->childNodes);
Executing the code shown above with PHP 7.3.16 (and newer) and PHP 7.4.4 (and newer) will print the output shown below:
object(DOMNodeList)#3 (1) {
["length"]=>
int(0)
}
Executing the same code with earlier versions will print the output shown below instead:
NULL
SimpleXML and Mathematical Operations
The simplexml extension provides a very simple and
easily usable API for working with XML. You can, for instance, use
the simplexml_load_string() function to load an XML
document from a string into a SimpleXMLElement object.
For some inexplicable reason, mathematical operations can be
performed on these objects:
$xml = simplexml_load_string(
'<?xml version="1.0" ?><root>1.5</root>'
);
var_dump($xml);
var_dump(2 * $xml);
Executing the code shown above with PHP 7.3 and newer will print the output shown below:
object(SimpleXMLElement)#1 (1) {
[0]=>
string(3) "1.5"
}
float(3)
Mathematical operations did not always work on
SimpleXMLElement as shown above. Prior to PHP 7.3
values were always treated as integers:
object(SimpleXMLElement)#1 (1) {
[0]=>
string(3) "1.5"
}
int(2)
2 * 1.5 is, of course, not 2. The
"1.5" string contained in the text node of the XML
element represented by the SimpleXMLElement object was
interpreted as an integer, the .5 part was cut off, and
2 * 1 was calculated.
Since PHP 7.3, mathematical operations involving
SimpleXMLElement objects treat the text as an integer
or float, whichever is more appropriate. At the end of the day,
performing such operations is a case where the phrase “Just because
you can, doesn’t mean you should” applies. We highly recommend that
you do not use the simplexml API at all. It can be good
for implementing a quick, one-off script, but it is not suited for
long-lived software in our opinion. Have a look at the
xmlreader extension for read-only processing of XML.
xmlwriter is a good choice for simple use cases of
creating XML documents. And dom is the API of choice
for all other use cases.