本文实例讲述了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互相转换工具:
在线格式化XML/在线压缩XML:
XML在线压缩/格式化工具:
XML代码在线格式化美化工具:
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP针对XML文件操作技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。