首页 > 解决方案 > PHP 致命错误:未捕获的错误:在 null 上调用成员函数 appendChild()

问题描述

我在尝试使用 json 字符串创建 HTML 元素时遇到问题。如果一个元素将主体作为父元素,它可以正常工作,但是我该如何将子元素附加到主体之外的任何东西上呢?在 Json 字符串中有一个名为“parent”的属性,该值是我要查找然后附加到的元素的 id。此时我试图通过 id 获取父元素,但我不断收到此错误。

PHP 致命错误:未捕获的错误:在 null 上调用成员函数 appendChild()

如何正确找到父元素?

提前致谢。

<?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();

?> 

标签: php

解决方案


推荐阅读