0

我正在使用 DOMDocument 来解析 XML 文件。我遍历不同的元素,看看是否缺少任何元素,然后用 createElement 填充一个数组,并显示错误消息。最后我试图 appendChild 该数组,但我总是收到相同的错误消息:

Uncaught exception 'DOMException' with message 'Wrong Document Error'
DOMNode->appendChild(Object(DOMElement))
1 {main}
thrown in /xxx/xxx.php on line 235
PHP Fatal error: Call to undefined method DOMElement::item() in /xxx/xxx.php on line 235.

代码如下:

$SMQuery = new DOMDocument();
$SMQuery->loadXML($params);
$response = $SMQuery->createElement('SMreply');
$errors = array();
if (!$reqtyp = $SMQuery->getElementsByTagName("tag1"))
{$errors[] = $SMQuery->createElement('error', 'tag1 Element is missing');}
if (!$reqtyp = $SMQuery->getElementsByTagName("tag2"))
{$errors[] = $SMQuery->createElement('error', 'tag2 Element is missing');}
......

if(!empty($errors))
{
 foreach($errors as $error) {
  $response->appendChild($error); <==== this line is causing the error !!!
 }
}

任何帮助深表感谢。干杯,瑞奇。

4

1 回答 1

2

你没有显示在哪里$response被定义,但如果它是另一个的结果new DOMDocument(),那么这就解释了你的错误——你不能直接将节点从一个 DOM 对象添加到另一个。它必须首先通过->importNode(). 只有在那之后,你才能真正附加它。

于 2012-02-02T14:30:21.173 回答