php读取xml文件总结

WBOY
Libérer: 2016-06-20 13:03:47
original
782 Les gens l'ont consulté

不久前做了个功能需要读取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>
Copier après la connexion

(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>";
}
Copier après la connexion

如需更详细的了解 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 />";
}
Copier après la connexion

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

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


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!