|
以下範例使用了PHP-XML基礎用法,不懂得可以告訴我再加以註解- <?php
- $string = <<<XML
- <?xml version='1.0'?>
- <Item>
- <user>
- <title>TITLE</title>
- <name>Nick</name>
- </user>
- </Item>
- XML;
-
- $xml = simplexml_load_string($string);
- print_r($xml);
- echo $obj->asXml();
- $obj->asXml('example.xml');
- ?>
複製代碼
另一個範例,主要是注意Header使用,才能讓瀏覽器辨別- <?php
- $newsXML = new SimpleXMLElement("<news></news>");
- $newsXML->addAttribute('newsPagePrefix', 'value goes here');
- $newsIntro = $newsXML->addChild('content');
- $newsIntro->addAttribute('type', 'latest');
- Header('Content-type: text/xml');
- echo $newsXML->asXML();
- ?>
複製代碼
補充一個simpleXML大問題:CDATA封裝
這裡引用一段範例解決此問題:- <?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);
- ?>
複製代碼 |
|