php基于dom实现读取图书xml格式数据的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php基于dom实现读取图书xml格式数据的方法。分享给大家供大家参考,具体如下:

<?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 - $publisher\n";
 }
?>

books.xml文件如下:

<?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>

运行结果如下:

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

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP针对XML文件操作技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP错误与异常处理方法总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

CentOS系统中PHP安装扩展的方式汇总

CentOS系统中PHP安装扩展的方式汇总

CentOS 下,PHP有多种方式来安装扩展, 主要有 包管理式 的 yum 安装 、 pecl 安装 , 以及 源码编译安装 。 包管理式 的安装卸载尤为方便,而 源码编译式 的安装则...

php+ajax实时输入自动搜索匹配的方法

本文实例讲述了php+ajax实输入自动搜索匹配的方法分享给大家供大家参考。具体分析如下: 第一种方法利用了jquery autocomplete,第二种使用了jquery ajax,其...

学习php笔记 字符串处理

substr(); substr(str,start,length); 例:substr('php is very good language',4,5); 输出为 is ve; 当st...

关于php unset对json_encode的影响详解

关于php unset对json_encode的影响详解

前言 PHP 中有个释放变量的语句叫做unset(从PHP4开始unset已经不再是一个函数了,而是一个语句),本文主要给大家介绍了关于php unset对json_encode影响的相...

PHP json_encode中文乱码问题的解决办法

下面的PHP代码可以解决以下问题:1.json_encode UTF8码中文后的字符串不可阅读2.json_encode 多级数组中文乱码问题3.json_encode 数组中包含换行时...