php - 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();
?>
解决方案
推荐阅读
- mysql - 节点 js 服务器,mysql db,返回不正确的日期值
- javascript - 自定义 Vimeo API 嵌入不在 Chrome 中自动播放
- python - Selenium Python - 网络驱动程序
- jenkins - 使用 Jenkins 版本 2.107.3 获得“致命:在 /root/apache-maven-3.5.3 中找不到任何可执行文件”。我是 CentOS
- mysql - 无法启动 mySQL “mysqld:参数太多(第一个额外是 'start')。”
- php - 使用 Symfony Finder 通过丢失文件排除目录
- python - Python - 语法无效
- c# - 从配置文件中获取设置
- nginx - 如何进行 nginx url 重写?
- swift - 有没有办法结合开关和包含?