php教程

超轻量级php框架startmvc

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

更新时间:2020-04-08 04:08:11 作者:startmvc
本文实例讲述了PHP读取XML文件的方法。分享给大家供大家参考,具体如下:使用DOMDocument对

本文实例讲述了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/在线压缩XMLhttp://tools.jb51.net/code/xmlformat

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

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

PHP 读取XML DOMDocument simplexml