您现在的位置是:网站首页> 编程资料编程资料

PHP读取XML文件的方法实例总结【DOMDocument及simplexml方法】_php技巧_

2023-05-25 269人已围观

简介 PHP读取XML文件的方法实例总结【DOMDocument及simplexml方法】_php技巧_

本文实例讲述了PHP读取XML文件的方法。分享给大家供大家参考,具体如下:

使用DOMDocument对象读取xml

创建一个DOMDocument对象

 $doc = new DOMDocument(); 

载入xml文件

 $doc->load("book.xml"); 

获取标签对象

 $books = $doc->getElementsByTagName("book"); 

获取标签的子对象

 $titles = $book->getElementsByTagName("title");

获取标签的值或属性

 $title = $titles->item(0)->nodeValue; 

实例1,获取图书列表

book.xml

PHP和MySQL开发谭浩强xml从入门到精通郑智化

load.php

load("book.xml"); //打开book.xml $books = $doc->getElementsByTagName("book"); //获取book标签对象 foreach ($books as $book){ //遍历对象 $titles = $book->getElementsByTagName("title"); //获取book标签下的title标签 $title = $titles->item(0)->nodeValue; //获取标签的值 $authors = $book->getElementsByTagName("author");//获取book标签下的author标签 $author = $authors->item(0)->nodeValue; //获取标签的值 $item["title"] = $title; $item["author"] = $author; $bookinfo[] = $item; } var_dump($bookinfo); 

实例2,读取配置文件

config.xml

127.0.0.1roottest

config.php

load("config.xml"); //打开config.xml $mysql = $doc->getElementsByTagName("mysql"); //获取mysql标签对象 $host = $mysql->item(0)->getElementsByTagName("host"); $config["host"] = $host->item(0)->nodeValue; $username = $mysql->item(0)->getElementsByTagName("username"); $config["username"] = $username->item(0)->nodeValue; $password = $mysql->item(0)->getElementsByTagName("password"); $config["password"] = $password->item(0)->nodeValue; $database = $mysql->item(0)->getElementsByTagName("database"); $config["database"] = $database->item(0)->nodeValue; var_dump($config); 

使用simplexml方法读取xml

实例1,获取图书列表

load.php

title; $item["author"] = $book->author; $booklist[] = $item; } var_dump($booklist); 

实例2,读取配置文件

config.php

host; $config['username'] = $mysql->username; $config['password'] = $mysql->password; $config['databse'] = $mysql->database; var_dump($config); 

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+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

-六神源码网