Home  >  Article  >  Backend Development  >  php读取xml文件总结

php读取xml文件总结

WBOY
WBOYOriginal
2016-06-20 13:03:47822browse

不久前做了个功能需要读取xml文件,虽然以前也做过很多次了,但一直没有想过总结一下,今天正好空闲,于是小小总结一番,以方便以后用起来更加顺手,下面开始正文。

假设目前有如下xml源文件,该文件保存名为books.xml:

<pre class="code"><?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <author>phpernote.com</author>
        <title>PHP And MySQL Development</title>
        <publisher>火星出版社</publisher>
    </book>
    <book>
        <author>taobao.com</author>
        <title>如何淘宝</title>
        <publisher>淘宝出版社</publisher>
    </book>
</books>

(1)利用simplexml读取xml文件,示例如下:

<pre class="code"><?php
header('Content-type:text/html;charset=utf-8');
$books=simplexml_load_file('books.xml');//将XML中的数据,读取到数组对象中
foreach($books as $v){
	echo $v->author."-".$v->title."-".$v->publisher."<br>";
}

如需更详细的了解 PHP SimpleXML 函数,请参考:PHP SimpleXML 函数

(2)利用DOMDocument读取xml文件,示例如下:

<pre class="code"><?php
header('Content-type:text/html;charset=utf-8');
$doc=new DOMDocument();
$doc->load('books.xml');//读取xml文件
$book=$doc->getElementsByTagName('book');//取得book标签的对象数组
echo $book->length,'<br />';
foreach($book as $v){
	$author=$v->getElementsByTagName('author');//取得author的标签的对象数组
	$author=$author->item(0)->nodeValue;//取得node中的值
	$title=$v->getElementsByTagName('title');
	$title=$title->item(0)->nodeValue;
	$publisher=$v->getElementsByTagName('publisher');
	$publisher=$publisher->item(0)->nodeValue;
	echo "$author - $title - $publisher <br />";
}

如需更详细的了解 DOMDocument 的有关方法,请参考php官方文档:The DOMDocument class

当然还有很多其他的办法,比如用正则表达式解析等等,这些以后用到的时候再继续追加总结,今天就写了这么两种办法吧,对于一般的已经足够了。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn