There is the same problem at xml to array - remove empty array php Dont know how you handle this. I mean how can i get an answer to a question that is not mine and asked > 2 years ago. So im asking here my own question:
Simple script:
$xml
= '<?xml version="1.0"?>
<Envelope>
<foo>
<bar>
<baz>Hello</baz>
<bat/>
</bar>
</foo>
<foo>
<bar>
<baz>Hello Again</baz>
<bat></bat>
</bar>
</foo>
<foo>
<bar>
<baz>Hello Again</baz>
<bat> </bat>
</bar>
</foo>
</Envelope>';
$xml = new \SimpleXMLElement(
$xml,
LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG | LIBXML_NOCDATA
);
$array = json_decode(json_encode((array)$xml), true);
// [
// 'foo' => [
// 0 => [
// 'bar' => [
// 'baz' => 'Hello',
// 'bat' => [], <<-- how to get this to NULL
// ],
// ],
// 1 => [
// 'bar' => [
// 'baz' => 'Hello Again',
// 'bat' => [], <<-- how to get this to NULL
// ],
// ],
// 2 => [
// 'bar' => [
// 'baz' => 'Hello Again',
// 'bat' => [ <<-- how to get this to NULL
// 0 => ' ', or at least to value of " " without array
// ],
// ],
// ],
// ],
// ];
As you can see there is an empty <bat/>
tag and a whitespace in the last <bat> </bat>
tag.
I would like to get those to null
in the array.
I tried the following but this works for the first level only ofc:
$data = (array)$xml;
foreach ($data as &$item) {
if (
$item instanceof \SimpleXMLElement
and $item->count() === 0
) {
// is a object(SimpleXMLElement)#1 (0) {}
$item = null;
}
}
I tried and failed doing this recursively.
Also tried RecursiveIteratorIterator
but failed.
But there must be a way to get those offset to null
.
Anybody done this before?
EDIT
Solved. See https://stackoverflow.com/a/55733384/3411766