PHP基于dom实现XML数据格式的操作:
1、读取xml格式数据方法
2、数据保存为xml格式方法
【1、读取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"; } ?>
xml文件内容:
<?xml version="1.0"?> <books> <book> <author>Jack Herrington</author> <title>PHP Hacks</title> <publisher>O'Reilly</publisher> </book> <book> <author>Jack Herrington</author> <title>Podcasting Hacks</title> <publisher>O'Reilly</publisher> </book> </books>
运行结果如下:
PHP Hacks - Jack Herrington - O'Reilly
Podcasting Hacks - Jack Herrington - O'Reilly
【2、数据保存为xml格式方法】
<?php $books = array(); $books [] = array( 'title' => 'PHP Hacks', 'author' => 'Jack Herrington', 'publisher' => "O'Reilly" ); $books [] = array( 'title' => 'Podcasting Hacks', 'author' => 'Jack Herrington', 'publisher' => "O'Reilly" ); $doc = new DOMDocument(); $doc->formatOutput = true; $r = $doc->createElement( "books" ); $doc->appendChild( $r ); foreach( $books as $book ){ $b = $doc->createElement( "book" ); $author = $doc->createElement( "author" ); $author->appendChild( $doc->createTextNode( $book['author'] ) ); $b->appendChild( $author ); $title = $doc->createElement( "title" ); $title->appendChild( $doc->createTextNode( $book['title'] ) ); $b->appendChild( $title ); $publisher = $doc->createElement( "publisher" ); $publisher->appendChild( $doc->createTextNode( $book['publisher'] ) ); $b->appendChild( $publisher ); $r->appendChild( $b ); } echo $doc->saveXML(); ?>
运行结果:
<?xml version="1.0"?>
<books>
<book>
<author>Jack Herrington</author>
<title>PHP Hacks</title>
<publisher>O'Reilly</publisher>
</book>
<book>
<author>Jack Herrington</author>
<title>Podcasting Hacks</title>
<publisher>O'Reilly</publisher>
</book>
</books>
转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/130.html
1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意