中央論壇 - CENTER BBS

標題: [PHP] XML基礎簡單範例 - simplexml 函數 / asXml() 函數 [打印本頁]

作者: 死神    時間: 2013-11-26 16:46
標題: [PHP] XML基礎簡單範例 - simplexml 函數 / asXml() 函數
以下範例使用了PHP-XML基礎用法,不懂得可以告訴我再加以註解
  1. <?php
  2. $string = <<<XML
  3. <?xml version='1.0'?>
  4. <Item>
  5.   <user>
  6.     <title>TITLE</title>
  7.     <name>Nick</name>
  8.   </user>
  9. </Item>
  10. XML;

  11. $xml = simplexml_load_string($string);
  12. print_r($xml);

  13. echo $obj->asXml();
  14. $obj->asXml('example.xml');
  15. ?>
複製代碼


另一個範例,主要是注意Header使用,才能讓瀏覽器辨別
  1. <?php
  2. $newsXML = new SimpleXMLElement("<news></news>");
  3. $newsXML->addAttribute('newsPagePrefix', 'value goes here');
  4. $newsIntro = $newsXML->addChild('content');
  5. $newsIntro->addAttribute('type', 'latest');
  6. Header('Content-type: text/xml');
  7. echo $newsXML->asXML();
  8. ?>
複製代碼



補充一個simpleXML大問題:CDATA封裝

這裡引用一段範例解決此問題:
  1. <?php
  2. // http://coffeerings.posterous.com/php-simplexml-and-cdata
  3. class SimpleXMLExtended extends SimpleXMLElement {
  4.   public function addCData($cdata_text) {
  5.     $node = dom_import_simplexml($this);
  6.     $no   = $node->ownerDocument;
  7.     $node->appendChild($no->createCDATASection($cdata_text));
  8.   }
  9. }

  10. $xmlFile    = 'config.xml';
  11. // instead of $xml = new SimpleXMLElement('<site/>');
  12. $xml        = new SimpleXMLExtended('<site/>');
  13. $xml->title = NULL; // VERY IMPORTANT! We need a node where to append
  14. $xml->title->addCData('Site Title');
  15. $xml->title->addAttribute('lang', 'en');
  16. $xml->saveXML($xmlFile);
  17. ?>
複製代碼





歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/) Powered by Discuz! X3