I think the best way would be to load it in DomDocument. I would prefer another parser for performance sake, but your form builder is not XHTML compatible, so we can not handle it as plain XML.
DomDocument has a function loadHTML
. This does not mind some unclosed input fields as long as it is valid HTML.
$html = '';
foreach ($fields as $field) {
$domDocument = new DomDocument();
$domDocument->loadHTML($field);
$html .= $domDocument->saveXML($domDocument->documentElement);
}
var_dump($html);
now we have a very annoying functionality of DomDocument. It automatically adds head and body tags.
luckily some other smart guys on SO know how to deal with this.
https://stackoverflow.com/a/6953808/2314708 (thank you Alex)
// remove <!DOCTYPE
$domDocument->removeChild($domDocument->firstChild);
// remove <html><body></body></html>
$domDocument->replaceChild($domDocument->firstChild->firstChild->firstChild, $domDocument->firstChild);
now we can manipulate the element we want with something like:
// I am asuming there is only one element and that one element should be modified. if it is otherwise just use another selector.
$element = $domDocument->documentElement;
$element->appendChild(new DOMAttr("value", "someValue"));
and when we put all of this together we can create exactly what we want.
//this would be in your DB or anywhere else.
$fields = array(
'<input id="test1">',
'<input id="test2">',
'<input id="test3" value="oldValue">',
'<input id="test4" value="oldValue">',
);
$values = array(
"test1" => 123, // set a new integer value
"test2" => "just a text", // set a new string value
"test3" => "newValue", // override an existing value
);
$domDocument = new DomDocument();
$html = '';
foreach ($fields as $field) {
$domDocument->loadHTML($field);
// now we have a very annoying functionality of DomDocument. It automatically adds head and body tags.
// remove <!DOCTYPE
$domDocument->removeChild($domDocument->firstChild);
// remove <html><body></body></html>
$domDocument->replaceChild($domDocument->firstChild->firstChild->firstChild, $domDocument->firstChild);
$element = $domDocument->documentElement;
$elementId = $element->getAttribute('id');
if (array_key_exists($elementId, $values)) {
// this adds an attribute or it overrides if it exists
$element->appendChild(new DOMAttr("value", $values[$elementId]));
}
$html .= $domDocument->saveXML($element);
}
var_dump($html);
for your radio/checkboxes you could use other ways of selecting your element and of course setting the correct type. Basically they would take just about as mutch work as a JS implementation, except you are not annoying the user's browser/system when you do it on the server.