三叶草 发表于 2021-11-9 18:35:34

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

这篇文章主要介绍了PHP读取XML文件的方法,结合实例形式总结分析了php基于DOMDocument及simplexml方法针对xml文件的载入、读取等相关操作技巧,需要的朋友可以参考下
本文实例讲述了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);
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/koastal/article/details/50705267

http://www.zzvips.com/article/184408.html
页: [1]
查看完整版本: PHP读取XML文件的方法实例总结【DOMDocument及simplexml方法】