Example of how PHP uses DOM and simplexml to read xml documents, domsimplexml
This example describes how PHP uses DOM and simplexml to read xml documents. We will share this with you for your reference. The details are as follows:
The instance uses DOM to obtain the names of all Jin Yong novels in the following xml documents. The xml document is located in./books. xml:
<? Xml version = "1.0" encoding = "UTF-8"?> <Root> <book> <title> tianlong Babu </title> <author> Jin Yong </author> </book> <title> Lu Xiaofeng </title> <author> gu Long </author> </book> <title> Yi Tian tu long Kee </title> <author> Jin Yong </author> </book> <title> travel to the west </title> <author> Wu chengen </author> </book> <title> Condor Heroes </title> <author> Jin Yong </author> </book> <book> <title> legend </title> <author> Jin Yong </author> </book> </root>
Implemented Using DOM code:
Steps for DOM reading xml documents: 1. Create a DOM object -- "2. Load the content of the DOM document --" 3. Extract the tag where the content to be read is located and obtain the content to be read.
Header ('content-type: text/html; charset = UTF-8 '); $ arr = array (); $ dom = new DOMDocument (); // create a DOM object $ dom-> load ('. /books. xml '); // load the xml document print_r ($ dom); echo'
GetElementsByTagName and childNodes are all returned objects, so they must be followed by item (int). Even if the returned objects contain only one project, item (0) must be specified, otherwise, an error occurs.
Implemented Using simplexml code:
$ Simxml = simplexml_load_file ('. /books. xml'); $ t = $ simxml-> book; $ arr = array (); foreach ($ t as $ v) {if ($ v-> author = 'jin Yong ') {$ arr [] = (string) $ v-> title ;}} print_r ($ arr );
Objects are returned after simplexml_load_file is used. The items in this object have both objects and arrays. Whether it is an object or an array, you can use foreach for the content in the loop. The final content $ v-> title obtained by the instance is actually an object, so it must be converted to a string.
PS: Here are some online tools for xml operations for your reference:
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
Online formatting XML/online compression XML:
Http://tools.jb51.net/code/xmlformat
XMLOnline compression/formatting tools:
Http://tools.jb51.net/code/xml_format_compress
XMLCode Online formatting and beautification tools:
Http://tools.jb51.net/code/xmlcodeformat