什麼是 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();
?>
以上就是這2段讀取和編寫XML的DOM代碼了,小伙伴們了解了沒,有什麼疑問可以給我留言