首页 > 开发 > PHP > 正文

php simpleXML添加CDATA格式数据

2024-05-04 21:48:12
字体:
来源:转载
供稿:网友

我们知道php中的simpleXML没办法直接很方便的添加CDATA格式的数据,这样对我们操作时会有一定的问题,下面我来给各位同学介绍php simpleXML添加CDATA格式数据一种办法,php实例代码如下:

  1. <?php 
  2. /** 
  3. * to show <title lang="en"><![CDATA[Site Title]]></title>   instead of <title lang="en">Site Title</title> 
  4. * 
  5. */ 
  6. class SimpleXMLExtended extends SimpleXMLElement 
  7.   { 
  8.   public function addCData($cdata_text
  9.     { 
  10.     $node = dom_import_simplexml($this); 
  11.     $no   = $node->ownerDocument; 
  12.     $node->appendChild($no->createCDATASection($cdata_text)); 
  13.     } 
  14.   }//开源代码Vevb.com 
  15. $xmlFile    = 'config.xml'
  16. // instead of $xml = new SimpleXMLElement('<sites/>'); 
  17. $xml = new SimpleXMLExtended('<sites/>'); 
  18. $site = $xml->addChild('site'); 
  19. // instead of $site->addChild('site', 'Site Title'); 
  20. $site->title = NULL; // VERY IMPORTANT! We need a node where to append 
  21. $site->title->addCData('Site Title'); 
  22. $site->title->addAttribute('lang''en'); 
  23. $xml->asXML($xmlFile); 
  24. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表