Home > Backend Development > PHP Tutorial > Implementation code for reading and writing XML DOM with PHP

Implementation code for reading and writing XML DOM with PHP

PHPz
Release: 2019-02-12 11:03:48
Original
857 people have browsed it

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>
Copy after login

DOM reading XML

The code is as follows:

<?php
$doc = new DOMDocument();
$doc->load( &#39;books.xml&#39; );
$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";
}
?>
Copy after login

Writing XML with DOM

The code is as follows:

<?php
$books = array();
$books [] = array(
&#39;title&#39; => &#39;PHP Hacks&#39;,
&#39;author&#39; => &#39;Jack Herrington&#39;,
);
$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[&#39;author&#39;] ));  //给标签添加内容
$b->appendChild( $author );                //将子标签 加入父标签
$r->appendChild( $b );                    //加入父标签中!
}
echo $doc->saveXML();
?>
Copy after login

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.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template