Skip to content

Commit f78be88

Browse files
authored
Update Form.php
1 parent ea2b144 commit f78be88

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/Form.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,4 +210,34 @@ public function renderDom(\DOMDocument $doc): \DOMElement
210210
}
211211
return $formElement;
212212
}
213+
214+
public function toString(bool $withRoot = true, bool $asHtml = true): string
215+
{
216+
// save the DOMElement to a string
217+
$domDocument = new \DOMDocument('1.0', 'UTF-8');
218+
$form = $this->renderDom($domDocument);
219+
$domDocument->appendChild($form);
220+
if ($asHtml) {
221+
// save the HTML to a string
222+
$str = $domDocument->saveHTML($form);
223+
} else {
224+
// format the output as XML (for testing purposes)
225+
$domDocument->formatOutput = true;
226+
$str = $domDocument->saveXML($form);
227+
}
228+
if (!$str) {
229+
throw new \RuntimeException('Failed to save XML');
230+
}
231+
if (!$withRoot) {
232+
$str = str_replace("\n ", "\n", $str);
233+
$str = preg_replace('/^<' . $this->tag . '[^>]*>/', '', $str);
234+
$str = preg_replace('/<\/' . $this->tag . '>$/', '', $str);
235+
}
236+
return trim($str);
237+
}
238+
239+
public function render(bool $withRoot = true): void
240+
{
241+
echo $this->toString($withRoot);
242+
}
213243
}

0 commit comments

Comments
 (0)