欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP 讀取和編寫 XML

 更新時間:2014年11月19日 09:03:49   投稿:hebedich  
本文主要介紹PHP 讀取和編寫 XML的方法,非常的簡單實(shí)用,給需要的小伙伴們參考下吧

什么是 XML?
XML 是一種數(shù)據(jù)存儲格式。它沒有定義保存什么數(shù)據(jù),也沒有定義數(shù)據(jù)的格式。XML 只是定義了標(biāo)記和這些標(biāo)記的屬性。格式良好的 XML 標(biāo)記看起來像這樣:

復(fù)制代碼 代碼如下:

<name>Jack Herrington</name>

DOM讀取 XML

復(fù)制代碼 代碼如下:

<?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

復(fù)制代碼 代碼如下:

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

以上就是這2段讀取和編寫XML的DOM代碼了,小伙伴們了解了沒,有什么疑問可以給我留言

相關(guān)文章

最新評論