如何使用 SimpleXmlElement 编写 CDATA?

2022-08-30 10:08:49

我有这个代码来创建和更新xml文件:

<?php
$xmlFile    = 'config.xml';
$xml        = new SimpleXmlElement('<site/>');
$xml->title = 'Site Title';
$xml->title->addAttribute('lang', 'en');
$xml->saveXML($xmlFile);
?>

这将生成以下 xml 文件:

<?xml version="1.0"?>
<site>
  <title lang="en">Site Title</title>
</site>

问题是:有没有办法用这种方法/技术添加CDATA来创建下面的xml代码?

<?xml version="1.0"?>
<site>
  <title lang="en"><![CDATA[Site Title]]></title>
</site>

答案 1

明白了!我从这个伟大的解决方案存档版本)中改编了代码:

    <?php
    
    // http://coffeerings.posterous.com/php-simplexml-and-cdata
    class SimpleXMLExtended extends SimpleXMLElement {

      public function addCData( $cdata_text ) {
        $node = dom_import_simplexml( $this ); 
        $no   = $node->ownerDocument;
        
        $node->appendChild( $no->createCDATASection( $cdata_text ) ); 
      }
    
    }

    $xmlFile    = 'config.xml';
    
    // instead of $xml = new SimpleXMLElement( '<site/>' );
    $xml        = new SimpleXMLExtended( '<site/>' );
    
    $xml->title = NULL; // VERY IMPORTANT! We need a node where to append
    
    $xml->title->addCData( 'Site Title' );
    $xml->title->addAttribute( 'lang', 'en' );
    
    $xml->saveXML( $xmlFile );
    
    ?>

生成的 XML 文件:

    <?xml version="1.0"?>
    <site>
      <title lang="en"><![CDATA[Site Title]]></title>
    </site>

谢谢佩塔


答案 2

以下是我的此类版本,它具有基于您的答案的快速addChildWithCDATA方法:

    Class SimpleXMLElementExtended extends SimpleXMLElement {

  /**
   * Adds a child with $value inside CDATA
   * @param unknown $name
   * @param unknown $value
   */
  public function addChildWithCDATA($name, $value = NULL) {
    $new_child = $this->addChild($name);

    if ($new_child !== NULL) {
      $node = dom_import_simplexml($new_child);
      $no   = $node->ownerDocument;
      $node->appendChild($no->createCDATASection($value));
    }

    return $new_child;
  }
}

只需这样使用它:

$node = new SimpleXMLElementExtended();
$node->addChildWithCDATA('title', 'Text that can contain any unsafe XML charachters like & and <>');

推荐