diff --git a/src/XlsxFastEditor.php b/src/XlsxFastEditor.php index 12c586a..17f029e 100644 --- a/src/XlsxFastEditor.php +++ b/src/XlsxFastEditor.php @@ -1028,13 +1028,20 @@ public function _makeNewSharedString(string $value): int } try { - $t = $dom->createElement('t', $value); + // First, we create an empty element t + $t = $dom->createElement('t'); + if ($t === false) { + throw new XlsxFastEditorXmlException('Failed to create element'); + } + // Add content as a text node + $textNode = $dom->createTextNode($value); + if ($textNode === false) { + throw new XlsxFastEditorXmlException('Failed to create text node'); + } + $t->appendChild($textNode); } catch (\DOMException $dex) { throw new XlsxFastEditorXmlException('Error creating in shared strings!', $dex->code, $dex); } - if ($t === false) { - throw new XlsxFastEditorXmlException('Error creating in shared strings!'); - } $si->appendChild($t); if (!($dom->firstElementChild instanceof \DOMElement)) { throw new XlsxFastEditorXmlException('Invalid shared strings!'); diff --git a/src/XlsxFastEditorCell.php b/src/XlsxFastEditorCell.php index 738579f..d568605 100644 --- a/src/XlsxFastEditorCell.php +++ b/src/XlsxFastEditorCell.php @@ -307,10 +307,17 @@ public function writeFormula(string $value): void throw new XlsxFastEditorXmlException("Internal error accessing cell {$this->name()}!"); } try { - $f = $dom->createElement('f', $value); - if (!($f instanceof \DOMElement)) { + // First, we create an empty element t + $f = $dom->createElement('f'); + if ($f === false) { throw new XlsxFastEditorXmlException("Error creating DOMElement of formula for cell {$this->name()}!"); } + // Add content as a text node + $textNode = $dom->createTextNode($value); + if ($textNode === false) { + throw new XlsxFastEditorXmlException("Error creating text node of formula for cell {$this->name()}!"); + } + $f->appendChild($textNode); } catch (\DOMException $dex) { throw new XlsxFastEditorXmlException("Error creating formula for cell {$this->name()}!", $dex->code, $dex); } diff --git a/tests/test.php b/tests/test.php index 66a688f..70fa78e 100644 --- a/tests/test.php +++ b/tests/test.php @@ -119,6 +119,10 @@ $xlsxFastEditor->writeInt($sheet2, 'C3', -7); $xlsxFastEditor->writeFloat($sheet2, 'D3', 273.15); + // Writing special XML characters + $xlsxFastEditor->writeString($sheet2, 'B5', '< " & \' >'); + $xlsxFastEditor->writeFormula($sheet2, 'C5', '=LEN("< & \' >")'); + // Writing non-existing cells but existing lines $xlsxFastEditor->writeFormula($sheet2, 'I2', '=7*3'); $xlsxFastEditor->writeString($sheet2, 'F2', 'γ'); @@ -166,6 +170,10 @@ assert($xlsxFastEditor->readString($sheet1, 'B2') === 'World'); + // Test special XML characters + assert($xlsxFastEditor->readString($sheet2, 'B5') === '< " & \' >'); + assert($xlsxFastEditor->readFormula($sheet2, 'C5') === '=LEN("< & \' >")'); + $xlsxFastEditor->close(); // Verify by hand that the resulting file opens without warning in Microsoft Excel.