我們知道php中的simpleXML沒辦法直接很方便的添加CDATA格式的數據,這樣對我們操作時會有一定的問題,下面我來給各位同學介紹php simpleXML添加CDATA格式數據一種辦法,php實例代碼如下:
- <?php
- /**
- * to show <title lang="en"><![CDATA[Site Title]]></title> instead of <title lang="en">Site Title</title>
- *
- */
- class SimpleXMLExtended extends SimpleXMLElement
- {
- public function addCData($cdata_text)
- {
- $node = dom_import_simplexml($this);
- $no = $node->ownerDocument;
- $node->appendChild($no->createCDATASection($cdata_text));
- }
- }//開源代碼Vevb.com
- $xmlFile = 'config.xml';
- // instead of $xml = new SimpleXMLElement('<sites/>');
- $xml = new SimpleXMLExtended('<sites/>');
- $site = $xml->addChild('site');
- // instead of $site->addChild('site', 'Site Title');
- $site->title = NULL; // VERY IMPORTANT! We need a node where to append
- $site->title->addCData('Site Title');
- $site->title->addAttribute('lang', 'en');
- $xml->asXML($xmlFile);
- ?>
新聞熱點
疑難解答