PHP:DOMNode::appendChild 到元素数组

发布于 2025-01-01 08:19:55 字数 1008 浏览 4 评论 0原文

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

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 !!!
 }
}

非常感谢任何帮助。 干杯, 瑞奇。

I am using DOMDocument to parse an XML file. I loop through the different Elements and see if any of them is missing and I fill an array with a createElement, with the error message. At the end I'm trying to appendChild that array but I always get the same error message:

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.

the code is as follow:

$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 !!!
 }
}

Any help is much appreciated.
Cheers,
Riki.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

却一份温柔 2025-01-08 08:19:55

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

You don't show where $response is being defined, but if it's the result of another new DOMDocument(), then that explains you error - you can't add nodes from one DOM object to another directly. It has to be imported first via ->importNode(). Only after that can you actually append it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文