歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> PHP 讀取和編寫 XML DOM

PHP 讀取和編寫 XML DOM

日期:2017/3/1 9:37:13   编辑:Linux編程

目錄

什麼是 XML?
DOM讀取 XML
用 DOM 編寫 XML

什麼是 XML?

XML 是一種數據存儲格式。它沒有定義保存什麼數據,也沒有定義數據的格式。XML 只是定義了標記和這些標記的屬性。格式良好的 XML 標記看起來像這樣:

<name>Jack Herrington</name>

DOM讀取 XML

<?php
  $doc = new DOMDocument();
  $doc->load( 'books.xml' );
  
  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;
  
  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;
  
  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;
  
  echo "$title - $author - $publisher\n";
  }
  ?>

用 DOM 編寫 XML

<?php
  $books = array();
  $books [] = array(
  'title' => 'PHP Hacks',
  'author' => 'Jack Herrington',
  );
  $doc = new DOMDocument(); //創建dom對象
  $doc->formatOutput = true;
  
  $r = $doc->createElement( "books" );//創建標簽
  $doc->appendChild( $r );            //將$r標簽,加入到xml格式中。
  
  foreach( $books as $book )
  {
      $b = $doc->createElement( "book" );        //創建標簽
      $author = $doc->createElement( "author" );
      $author->appendChild($doc->createTextNode( $book['author'] ));  //給標簽添加內容
      $b->appendChild( $author );                //將子標簽 加入父標簽
      
      
      $r->appendChild( $b );                    //加入父標簽中!
      }
      
      echo $doc->saveXML();
  ?>

CentOS 6.3 安裝LNMP (PHP 5.4,MyySQL5.6) http://www.linuxidc.com/Linux/2013-04/82069.htm

在部署LNMP的時候遇到Nginx啟動失敗的2個問題 http://www.linuxidc.com/Linux/2013-03/81120.htm

Ubuntu安裝Nginx php5-fpm MySQL(LNMP環境搭建) http://www.linuxidc.com/Linux/2012-10/72458.htm

《細說PHP》高清掃描PDF+光盤源碼+全套教學視頻 http://www.linuxidc.com/Linux/2014-03/97536.htm

PHP 的詳細介紹:請點這裡
PHP 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved