0

I am having a problem trying to use a json string to create HTML elements. If an element has the body as a parent it works fine, but how do I go about appending a child element to anything but the body? Inside the Json string there is a property called "parent" this value is the id of the element that I am trying to find and then append to. At this point I am trying to get the parent element by id, but I keep getting this error.

PHP Fatal error: Uncaught Error: Call to a member function appendChild() on null

How do I properly find the parent element?

Thanks in advance.

<?php

$domDocument = new DOMDocument('1.0');
$root = $domDocument->createElement('html');
$root = $domDocument->appendChild($root);
$head = $domDocument->createElement('head');
$head = $root->appendChild($head);
$title = $domDocument->createElement('title');
$title = $head->appendChild($title);
$text = $domDocument->createTextNode('DOMDocument::saveHTML() function');
$text = $title->appendChild($text);
$body = $domDocument->createElement('body');
$body = $root->appendChild($body);

$json = '[{"tag":"div","id":"createNewUserForm","parent":"body","class":"w3-green"},{"tag":"h3","id":"userLabel","parent":"createNewUserForm","contents":"Username:"},{"tag":"h3","id":"passLabel","parent":"createNewUserForm","contents":"password:"}]';
$element = json_decode($json,true);

for($x=0;$x<COUNT($element);$x++){
$el[$x] = $domDocument->createElement($element[$x]["tag"]);
$el[$x]->setAttribute('id', $element[$x]["id"]);
if($element[$x]["parent"]=="body"){
    $el[$x] = $body->appendChild($el[$x]);
}else{
    $el[$x] = $domDocument->getElementById($element[$x]["parent"])->appendChild($el[$x]);
}
if(isset($element[$x]["class"])){
    $el[$x]->setAttribute('class', $element[$x]["class"]);
}

if(isset($element[$x]["contents"])){
$contents[$x] = $domDocument->createTextNode($element[$x]["contents"]);
$contents[$x] = $el[$x]->appendChild($contents[$x]);
}

}

echo $domDocument->saveHTML();

?> 

0 Answers0