Home >Backend Development >PHP Tutorial >Implementation code for reading and writing XML DOM with PHP
PHP reading and writing XML
This article mainly introduces the method of reading and writing XML in PHP. It is very simple and practical. Please refer to it for friends who need it. [Recommended tutorial: php introductory tutorial]
What is XML?
XML is a data storage format. It does not define what data is saved, nor does it define the format of the data. XML simply defines tags and the attributes of those tags. A well-formed XML markup looks like this:
The code is as follows:
<name>Jack Herrington</name>
DOM reading XML
The code is as follows:
<?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"; } ?>
Writing XML with DOM
The code is as follows:
<?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(); ?>
The above are the two paragraphs of reading and I have written the XML DOM code. Do you understand it? If you have any questions, please leave me a message.