Skip to content

Commit e20bfb0

Browse files
Allow _value content to be numeric (#248)
1 parent f707107 commit e20bfb0

File tree

4 files changed

+18
-4
lines changed

4 files changed

+18
-4
lines changed

README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,11 @@ $array = [
9292
'The survivor' => [
9393
'_attributes' => ['house'=>'Hogwarts'],
9494
'_value' => 'Harry Potter'
95-
]
95+
],
96+
'Good movie' => [
97+
'_attributes' => ['category' => 'Action'],
98+
'_value' => 300,
99+
],
96100
];
97101

98102
$result = ArrayToXml::convert($array);
@@ -114,6 +118,7 @@ This code will result in:
114118
<The_survivor house="Hogwarts">
115119
Harry Potter
116120
</The_survivor>
121+
<Good_movie category="Action">300</Good_movie>
117122
</root>
118123
```
119124

src/ArrayToXml.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,11 +172,11 @@ protected function convertElement(DOMElement $element, mixed $value): void
172172
if (! $sequential) {
173173
if (($key === '_attributes') || ($key === '@attributes')) {
174174
$this->addAttributes($element, $data);
175-
} elseif ((($key === '_value') || ($key === '@value')) && is_string($data)) {
175+
} elseif ((($key === '_value') || ($key === '@value')) && is_scalar($data)) {
176176
$element->nodeValue = htmlspecialchars($data);
177-
} elseif ((($key === '_cdata') || ($key === '@cdata')) && is_string($data)) {
177+
} elseif ((($key === '_cdata') || ($key === '@cdata')) && is_scalar($data)) {
178178
$element->appendChild($this->document->createCDATASection($data));
179-
} elseif ((($key === '_mixed') || ($key === '@mixed')) && is_string($data)) {
179+
} elseif ((($key === '_mixed') || ($key === '@mixed')) && is_scalar($data)) {
180180
$fragment = $this->document->createDocumentFragment();
181181
$fragment->appendXML($data);
182182
$element->appendChild($fragment);

tests/ArrayToXmlTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,12 @@
209209
'_value' => 'tom & jerry',
210210
],
211211
],
212+
[
213+
'title' => [
214+
'_attributes' => ['category' => 'Action'],
215+
'_value' => 300,
216+
],
217+
],
212218
],
213219
]));
214220
});

tests/__snapshots__/ArrayToXmlTest__it_can_handle_values_set_with_attributes_with_special_characters__1.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,7 @@
66
<movie>
77
<title category="Children">tom &amp; jerry</title>
88
</movie>
9+
<movie>
10+
<title category="Action">300</title>
11+
</movie>
912
</root>

0 commit comments

Comments
 (0)