首页  >  文章  >  后端开发  >  如何使用 SimpleXmlElement 将 CDATA 部分添加到 XML 文件?

如何使用 SimpleXmlElement 将 CDATA 部分添加到 XML 文件?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-23 13:30:30800浏览

How to Add CDATA Sections to XML Files with SimpleXmlElement?

使用 SimpleXmlElement 写入 CDATA

使用 SimpleXmlElement 创建和更新 XML 文件时,您可能会遇到需要添加 CDATA 部分的情况。下面是使用基类的扩展来实现此目的的定制解决方案:

自定义 SimpleXMLElement 类

为了避免与本机 SimpleXmlElement 类发生冲突,我们定义自定义类 SimpleXMLExtended:

<code class="php">class SimpleXMLExtended extends SimpleXMLElement {

  // Create CDATA section custom function.
  public function addCData( $cdata_text ) {
    $node              = dom_import_simplexml( $this ); 
    $ownerDocumentNode = $node->ownerDocument;

    $node->appendChild( $ownerDocumentNode->createCDATASection( $cdata_text )); 
  }

}</code>

示例用法

有了我们的扩展类,让我们来处理具体示例:

<code class="php">// Name of the XML file.
$xmlFile    = 'config.xml';

// <?xml version=&quot;1.0&quot;?>
// <site></site>
// ^^^^^^^^^^^^^
$xml        = new SimpleXMLExtended( '<site/>' );

// Insert '<title><title>' into '<site></site>'.
// <?xml version=&quot;1.0&quot;?>
// <site>
//   <title></title>
//   ^^^^^^^^^^^^^^^
// </site>
$xml->title = NULL; // IMPORTANT! Need a node where to append.

// CDATA section custom function.
// <?xml version=&quot;1.0&quot;?>
// <site></site></code>

以上是如何使用 SimpleXmlElement 将 CDATA 部分添加到 XML 文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn