源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP使用DOM和simplexml读取xml文档的方法示例

  • 时间:2022-04-26 23:57 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP使用DOM和simplexml读取xml文档的方法示例
本文实例讲述了PHP使用DOM和simplexml读取xml文档的方法。分享给大家供大家参考,具体如下: 实例  用DOM获取下列xml文档中所有金庸小说的书名,该xml文档所在位置为 ./books.xml:
<?xml version="1.0" encoding="utf-8"?>
<root>
 <book>
  <title>天龙八部</title>
  <author>金庸</author>
 </book>
 <book>
  <title>陆小凤</title>
  <author>古龙</author>
 </book>
 <book>
  <title>倚天屠龙记</title>
  <author>金庸</author>
 </book>
 <book>
  <title>西游记</title>
  <author>吴承恩</author>
 </book>
 <book>
  <title>神雕侠侣</title>
  <author>金庸</author>
 </book>
 <book>
  <title>射雕英雄传</title>
  <author>金庸</author>
 </book>
</root>

[b]用DOM代码实现:[/b] DOM读取xml文档步骤:1、创建DOM对象——》2、载入DOM文档内容——》3、截取要读取内容所在的标签——》获得要读取的内容。
header('Content-type:text/html;charset=utf-8');
$arr=array();
$dom = new DOMDocument();//创建DOM对象
$dom->load('./books.xml');//载入xml文档
print_r($dom);
echo '<hr>';
$dom = $dom->getElementsByTagName('book');//截取标签
for($i=0;$i<$dom->length;$i++){
 if($dom->item($i)->childNodes->item(1)->childNodes->item(0)->wholeText=='金庸'){
  $arr[] = $dom->item($i)->childNodes->item(0)->childNodes->item(0)->wholeText.'<br />';//获取内容
 }
}
print_r($arr);

使用 getElementsByTagName 和 childNodes 后返回的都是对象,所以它们后面必须使用 item(int),哪怕它们返回的对象里面只包含一个项目,也必须用item(0)来指定,否则就会出错。 [b]用simplexml代码实现:[/b]
$simxml = simplexml_load_file('./books.xml');
$t = $simxml->book;
$arr=array();
foreach ($t as $v){
 if($v->author=='金庸'){
  $arr[] = (string)$v->title;
 }
}
print_r($arr);

使用 simplexml_load_file 后返回的是对象,该对象里的项目既有对象又有数组,不管是对象还是数组,要循环里面的内容都可以用 foreach。该实例最后获取的内容 $v->title 其实是个对象,所以要用 string 转化为字符串。 [b]PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:[/b] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]在线格式化XML/在线压缩XML: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]XML[/b][b]在线压缩/格式化工具: [/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url] [b]XML[/b][b]代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] 更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/234.htm]PHP针对XML文件操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/196.htm]PHP错误与异常处理方法总结[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部