<Books>
<Book>
<Author> jack herrington </author>
<Title> php Tutorial hacks </title>
<Publisher> o 'Reilly </publisher>
</Book>
<Book>
<Author> jack herrington </author>
<Title> podcasting hacks </title>
<Publisher> o 'Reilly </publisher>
</Book>
</Books>
Xml in 1 contains a list of books. The parent tag <books> contains a set of <book> tags. Each <book> tag contains <author>, <title>, and <publisher> tags.
After the xml document's tag structure and content are verified by the external mode file, the xml document is correct. Mode files can be specified in different formats. For this article, all we need is a well-formatted xml.
If xml looks like html, that's right. Xml and html are both tag-based languages with many similarities. However, it is important to note that although xml documents may be well-formed html documents, not all html documents are well-formed xml documents. Line Feed mark (br) is a good example of the difference between xml and html. This line feed mark is html in good format, but not xml in good format:
<P> this is a paragraph <br>
With a line break </p>
This line feed mark is a well-formatted xml and html:
<P> this is a paragraph <br/>
With a line break </p>
If you want to write html into xml in the same good format, follow the w3c Committee's Extensible HyperText Markup Language (xhtml) standard. All modern browsers can render xhtml. In addition, you can use xml tools to read xhtml and find the data in the document, which is much easier than parsing html.
Use the dom library to read xml
The easiest way to read well-formed xml files is to compile them into some php-installed Document Object Model (dom) libraries. The dom library reads the entire xml document into the memory and uses the node tree to represent it, as shown in Figure 1.
Figure 1. xml dom tree of library xml
The books node on the top of the tree has two book subtags. In each book, there are several nodes: author, publisher, and title. The author, publisher, and title nodes contain text subnodes.
The code for reading the xml file of a book and displaying the content in dom is shown in list 2.
Listing 2. Reading library xml with dom
Copy the code 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-$ publishern ";
}
?>