Skip to content

Commit 0ef041c

Browse files
committed
Improve XML element creation and add tests for special character handling (eq. &)
1 parent 62c771a commit 0ef041c

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/XlsxFastEditor.php

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,13 +1028,17 @@ public function _makeNewSharedString(string $value): int
10281028
}
10291029

10301030
try {
1031-
$t = $dom->createElement('t', $value);
1031+
// First, we create an empty element t
1032+
$t = $dom->createElement('t');
1033+
if ($t === false) {
1034+
throw new XlsxFastEditorXmlException('Failed to create <t> element');
1035+
}
1036+
// Add content as a text node
1037+
$textNode = $dom->createTextNode($value);
1038+
$t->appendChild($textNode);
10321039
} catch (\DOMException $dex) {
10331040
throw new XlsxFastEditorXmlException('Error creating <t> in shared strings!', $dex->code, $dex);
10341041
}
1035-
if ($t === false) {
1036-
throw new XlsxFastEditorXmlException('Error creating <t> in shared strings!');
1037-
}
10381042
$si->appendChild($t);
10391043
if (!($dom->firstElementChild instanceof \DOMElement)) {
10401044
throw new XlsxFastEditorXmlException('Invalid shared strings!');
@@ -1048,7 +1052,7 @@ public function _makeNewSharedString(string $value): int
10481052
$dom->firstElementChild->setAttribute('uniqueCount', (string)$uniqueCount);
10491053

10501054
$this->touchPath(self::SHARED_STRINGS_PATH);
1051-
return $uniqueCount - 1; // Base 0
1055+
return $uniqueCount - 1; // Base 0
10521056
}
10531057

10541058
/**

tests/test.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,9 @@
119119
$xlsxFastEditor->writeInt($sheet2, 'C3', -7);
120120
$xlsxFastEditor->writeFloat($sheet2, 'D3', 273.15);
121121

122+
// Test writing special character '&'
123+
$xlsxFastEditor->writeString($sheet2, 'A5', '&');
124+
122125
// Writing non-existing cells but existing lines
123126
$xlsxFastEditor->writeFormula($sheet2, 'I2', '=7*3');
124127
$xlsxFastEditor->writeString($sheet2, 'F2', 'γ');
@@ -166,6 +169,9 @@
166169

167170
assert($xlsxFastEditor->readString($sheet1, 'B2') === 'World');
168171

172+
// Test writing special character '&'
173+
assert($xlsxFastEditor->readString($sheet2, 'A5') === '&');
174+
169175
$xlsxFastEditor->close();
170176

171177
// Verify by hand that the resulting file opens without warning in Microsoft Excel.

0 commit comments

Comments
 (0)