This article mainly introduces how PHP uses DOM and simplexml to read xml documents, and analyzes related operation skills for creating, loading, and reading xml files using DOM and simplxml in php in combination with examples, for more information about how to use DOM and simplexml to read xml documents in PHP, this article analyzes the creation, loading, and reading of xml files by using DOM and simplxml in php in the form of examples. For more information, see
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:
Tianlong BabuJin Yong
Lu XiaofengGu Long
Yi Tian Tu Long KeeJin Yong
Travel to the WestWu Chengen
Condor HeroesJin Yong
Legend of the Condor HeroJin Yong
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 ''; $ dom = $ dom-> getElementsByTagName ('book '); // capture the tag for ($ I = 0; $ I <$ dom-> length; $ I ++) {if ($ dom-> item ($ I) -> childNodes-> item (1)-> childNodes-> item (0)-> wholeText = 'jinyong ') {$ arr [] = $ dom-> item ($ I)-> childNodes-> item (0)-> childNodes-> item (0)-> wholeText.'
'; // Get content} print_r ($ arr );
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.
For more information about how to use DOM and simplexml to read xml documents, see PHP!