简体   繁体   English

如何获取DomElement的字符串?

[英]How to get string for a DomElement?

I have a DomElement which unfortunately does not have the saveXML() method that DomDocument has. 我有DomElement不幸的是不具有saveXML()这个方法DomDocument了。

I am trying to get the raw XML string representation of the of the DomElement. 我试图获取DomElement的原始XML字符串表示。

How can I do it? 我该怎么做?

The DomElement has a property of its DomDocument , ie ownerDocument . DomElement具有其DomDocument的属性,即ownerDocument

Hence you can fetch the XML of the DomElement via: 因此,您可以通过以下方式获取DomElement的XML:

$domElementXml = $domElement->ownerDocument->saveXML($domElement);

You have to pass the node again as the ownerDocument refers to the whole document. 您必须再次传递节点,因为ownerDocument引用整个文档。 So running $domElement->ownerDocument->saveXML() would fetch the entire XML of the document which could contain different DomElement objects as well. 因此,运行$domElement->ownerDocument->saveXML()将获取可能包含不同DomElement对象的文档的整个XML。

This expands on k0pernikus answer and includes a SimpleXMLElement variation. 这扩展了k0pernikus答案并包含SimpleXMLElement变体。 It works for any random DOM element without dumping the document XML: 它适用于任何随机DOM元素而不转储文档XML:

<?php

$outerXmlAsString = $yourDomElementGoesHere
    ->ownerDocument
    ->saveXML($yourDomElementGoesHere);

// or

$outerXmlAsString = simplexml_import_dom($yourDomElementGoesHere)
    ->asXML();

Example: 例:

<?php

$doc = new DOMDocument('1.0','utf-8');
$root = new DOMElement('root');
$doc->appendChild($root);
$child = new DOMElement('child');
$root->appendChild($child);
$leaf = new DOMElement('leaf','text');
$child->appendChild($leaf);

echo $child->ownerDocument->saveXML($child), PHP_EOL;
echo simplexml_import_dom($child)->asXML(), PHP_EOL;

Example output: 示例输出:

<child><leaf>text</leaf></child>
<child><leaf>text</leaf></child>

Test it out on 3v4l.org . 3v4l.org上测试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM