本文实例讲述了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
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book> <title>PHP和MysqL开发</title> <author>谭浩强</author> </book> <book> <titile>xml从入门到精通</titile> <author>郑智化</author> </book> </bookstore>
load.PHP
<?PHP header("Content-type:text/html;charset=utf8"); $doc = new DOMDocument(); //创建DOMDocument对象 $doc->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
<?xml version="1.0" encoding="UTF-8"?> <MysqL> <host>127.0.0.1</host> <username>root</username> <password></password> <database>test</database> </MysqL>
config.PHP
<?PHP header("Content-type:text/html;charset=utf8"); $doc = new DOMDocument(); //创建DOMDocument对象 $doc->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
<?PHP header("Content-type:text/html;charset=utf8"); $books = simplexml_load_file("book.xml"); foreach($books as $book){ $item["title"] = $book->title; $item["author"] = $book->author; $booklist[] = $item; } var_dump($booklist);
实例2,读取配置文件
config.PHP
<?PHP header("Content-type:text/html;charset=utf8"); $MysqL = simplexml_load_file("config.xml"); $config['host'] = $MysqL->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程序设计有所帮助。