PHP 8.5.0 Beta 1 available for testing

Voting

: three plus three?
(Example: nine)

The Note You're Voting On

Pyetro Costa [pyetrosafe at gmail dot com]
6 years ago
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
}
}
?>

<< Back to user notes page

To Top