使用SimpleXML處理XML

來源:互聯網
上載者:User
在開發Web應用時,為了減輕讀寫資料庫的I/O開銷,常常將一些配置資訊儲存在一般檔案如:XML,json中,然後通過指令碼語言如:PHP,javascript來操作這些檔案。
PHP操作XML主要有兩種方法:一種是通過DOM,另一種是通過SimpleXML。這兩種方法解析XML的原理都是分析整個XML文檔,並提供API來訪問樹中元素。SimpleXML是PHP 5新增的特性,目的是為了簡便完成一些XML的常見處理任務。
下面是一個簡單樣本,展示如何通過SimpleXML來格式化一組XML資料。
  1. Belgian Waffles
  2. $5.95
  3. two of our famous Belgian Waffles with plenty of real maple syrup
  4. 650
  5. Strawberry Belgian Waffles
  6. $7.95
  7. light Belgian waffles covered with strawberries and whipped cream
  8. 900
  9. Berry-Berry Belgian Waffles
  10. $8.95
  11. light Belgian waffles covered with an assortment of fresh berries and whipped cream
  12. 900
複製代碼
  1. 使用simpleXML處理XML
  2. // 使用simpleXML處理XML
  3. foreach ($child->children() as $item)
  4. }
  5. }
  6. $xml = simplexml_load_file('./simple.xml');
  7. //var_dump($xml);
  8. //echo $xml->getName();
  9. //var_dump($xml->children());
  10. $record = '';
  11. foreach ($xml->children() as $child)
  12. {
  13. $record .= '
  14. ';
  15. {
  16. //var_dump($child);
  17. $record .= '
  18. ';
  19. $record .= '
  20. ';
  21. echo $record;
  22. ?>
  23. name price description calories
    '. $child->attributes(). ' '. $item .'
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.