Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ This code will result in:
</root>
```

> [!NOTE]
> A comment will be omitted if the value is an empty string "" or `null`.

### Using reserved characters

It is also possible to wrap the value of a node into a CDATA section. This allows you to use reserved characters.
Expand Down
4 changes: 3 additions & 1 deletion src/ArrayToXml.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ protected function convertElement(DOMElement $element, mixed $value): void
} elseif (str_starts_with($key, '__custom:')) {
$this->addNode($element, str_replace('\:', ':', preg_split('/(?<!\\\):/', $key)[1]), $data);
} elseif (str_starts_with($key, '_comment') || str_starts_with($key, '@comment')) {
$element->appendChild(new \DOMComment($data));
if ($data !== null && $data !== '') {
$element->appendChild(new \DOMComment($data));
}
} else {
$this->addNode($element, $key, $data);
}
Expand Down
14 changes: 14 additions & 0 deletions tests/ArrayToXmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,20 @@
assertMatchesXmlSnapshot(ArrayToXml::convert($withAttributes));
});

it('null and empty comments are ignored', function () {
$withAttributes = $this->testArray;
$withAttributes['Another guy'] = [
'_comment' => null,
'name' => 'John Wick',
'_comment2' => '',
'weapon' => 'Pencil',
'_comment_deaths' => 0,
'lives' => 'more than 9 lives'
];

assertMatchesSnapshot(ArrayToXml::convert($withAttributes, domProperties: ['formatOutput' => true]));
});

test('and a comment also can be set in SimpleXMLElement style', function () {
$withAttributes = $this->testArray;
$withAttributes['Good guy']['@comment'] = 'Very short list';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<root>
<Good_guy>
<name>Luke Skywalker</name>
<weapon>Lightsaber</weapon>
</Good_guy>
<Bad_guy>
<name>Sauron</name>
<weapon>Evil Eye</weapon>
</Bad_guy>
<Another_guy>
<name>John Wick</name>
<weapon>Pencil</weapon>
<!--0-->
<lives>more than 9 lives</lives>
</Another_guy>
</root>