SoFunction
Updated on 2025-03-10

PHP method to read book XML format data based on dom

This article describes the method of reading xml format data in PHP based on DOM. Share it for your reference, as follows:

<?php
 $doc = new DOMDocument();
 $doc->load( '' );
 $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";
 }
?>

The file is as follows:

<?xml version="1.0"?>
<books>
 <book>
  <author>Jack Herrington</author>
  <title>PHP Hacks</title>
  <publisher>O'Reilly</publisher>
 </book>
 <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
 </book>
</books>

The operation results are as follows:

PHP Hacks - Jack Herrington - O'Reilly
Podcasting Hacks - Jack Herrington - O'Reilly

PS: Here are a few online tools for your reference:

Online XML/JSON mutual conversion tool:
http://tools./code/xmljson

Online formatting/online compressing XML:
http://tools./code/xmlformat

XML online compression/formatting tools:
http://tools./code/xml_format_compress

XML code online formatting and beautification tool:
http://tools./code/xmlcodeformat

For more information about PHP related content, please check out the topic of this site:Summary of PHP's XML file operation skills》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《Summary of PHP error and exception handling methods》、《Introduction to PHP basic syntax》、《PHP object-oriented programming tutorial》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.