在 PHP 中将 XML 附加到 DOMNode [英] Append XML to DOMNode in PHP

查看:23
本文介绍了在 PHP 中将 XML 附加到 DOMNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 XML 附加到 DOMNode 元素,但出现错误:文档错误".

I would like to append XML to DOMNode element, but I got the error : "Wrong Document Error".

这是我的代码:

$dom = new \DOMDocument();
$dom->loadXML($xmlResources->asXml());
$orderNodeList = $dom->getElementsByTagName('order');

foreach ($orderNodeList as $orderNode) {
    $idAddressDelivery = $orderNode->getElementsByTagName('id_address_delivery')->item(0)->nodeValue;
    $xmlToAppend = $this->getSpecificResource('addresses', $idAddressDelivery); //It returns a SimpleXMLElement

    $tmpNode = new \DOMDocument(); //I create a DOMDocument
    $tmpNode->loadXML($xmlToAppend->asXML()); //I fill it with XML

    $orderNode->appendChild($tmpNode); //I want to put the new XML inside the DOMNode, but it throws an error
}

我在网上搜索过,但不知道如何制作,请您告诉我有什么问题吗?

I've searched on the web, but don't know how to make it, could you tell what's wrong please ?

谢谢你的帮助^^

推荐答案

节点位于单独的 DOM 中.但是您只能附加属于同一 DOM 的节点.这里有两种可能:

The nodes are in a separate DOM. But you can only append nodes that are part of the same DOM. Here are two possibilities:

导入您加载的节点.

$target = new DOMDocument();
$target->loadXml("<one/>");

$source = new DOMDocument();
$source->loadXml("<two/>");

$target->documentElement->appendChild(
  $target->importNode($source->documentElement, TRUE)
);

echo $target->saveXml();

将 XML 加载到片段中并附加它.

Load the XML into a fragment and append it.

$target = new DOMDocument();
$target->loadXml("<one/>");

$fragment = $target->createDocumentFragment();
$fragment->appendXml("<two/>");

$target->documentElement->appendChild($fragment);

echo $target->saveXml();

输出:

<?xml version="1.0"?>
<one><two/></one>

提示:您可能想了解 DOMXpath::evaluate().它允许使用表达式获取节点.这比 DOMNode::getElementsByTagName() 之类的方法要强大得多.

HINT: You might want to read about DOMXpath::evaluate(). It allows to fetch nodes using expressions. This is a lot more powerful then methods like DOMNode::getElementsByTagName().

这篇关于在 PHP 中将 XML 附加到 DOMNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆