您好,欢迎访问一九零五行业门户网

PHP读写XML文件

php读写xml文件 author:morewindows blog: http://blog.csdn.net/morewindows keyword: php 解析xml domdocument xml文件操作 php可以方便的生成和读取xml文件。php主要通过domdocument、domelement和domnodelist来完成xml的读取与写入操作的。下面就简要说
php读写xml文件
author: morewindows
blog:    http://blog.csdn.net/morewindows
keyword:    php 解析xml domdocument xml文件操作
php可以方便的生成和读取xml文件。php主要通过domdocument、domelement和domnodelist来完成xml的读取与写入操作的。下面就简要说明下如何使用这些类。
一.生成xml文件对于一个如下xml文件。
php访问mysql数据库 初级篇http://blog.csdn.net/morewindows/article/details/7102362
我们来看看如何用php来生成:
首先new一个domdocument对象并设置编码格式。
$dom = newdomdocument('1.0', 'utf-8');
$dom->formatoutput= true;
再创建结点和结点
$rootelement =$dom->createelement(article);
$title =$dom->createelement(title, php访问mysql数据库 初级篇);
然后创建带文本内容的结点
$link =$dom->createelement(link,http://blog.csdn.net/morewindows/article/details/7102362);
也可以先生成结点再为其添加文本内容。
$link = $dom->createelement(link);
$linktext =$dom->createtextnode('http://blog.csdn.net/morewindows/article/details/7102362');
$link->appendchild($linktext);
然后将和结点加入到结点中去
$rootelement->appendchild($title);
$rootelement->appendchild($link);
最后将结点加入到domdocument对象中,
$dom->appendchild($rootelement);
这样一个完整的xml就生成完毕了。再整出整个xml,
echo $dom->savexml() ;
savexml()也可以只输入部分xml文本,如echo $dom->savexml($link);就只会输出结点:http://blog.csdn.net/morewindows/article/details/7102362>
下面再给出一个完整的php中数据内容输出到xml文件的例子。该例子会对将一个php数组输出到xml文件中。
array( title=>php访问mysql数据库 初级篇, link=>http://blog.csdn.net/morewindows/article/details/7102362 ), 第二篇 => array( title=>php访问mysql数据库 中级篇 smarty技术, link=>http://blog.csdn.net/morewindows/article/details/7094642 ), 第三篇 => array( title=>php访问mysql数据库 高级篇 ajax技术, link=>http://blog.csdn.net/morewindows/article/details/7086524 ),);$dom = new domdocument('1.0', 'utf-8');$dom->formatoutput = true;$rootelement = $dom->createelement(morewindows);foreach ($article_array as $key=>$value){ $article = $dom->createelement(article, $key); $title = $dom->createelement(title, $value['title']); $link = $dom->createelement(link, $value['link']); $article->appendchild($title); $article->appendchild($link); $rootelement->appendchild($article);}$dom->appendchild($rootelement);$filename = d:\\test.xml;echo 'xml文件大小' . $dom->save($filename) . '字节';?>
运行该php会在d盘上生成test.xml文件(win7 + xampp + ie9.0测试通过)
二.读取xml文件   以读取前文中生成的d:\\test.xml为例:
load($filename);//得到结点$articles = $dom->getelementsbytagname(article);echo ' 结点个数 ' . $articles->length;foreach ($articles as $article){ $id = $article->getelementsbytagname(id)->item(0)->nodevalue; $title = $article->getelementsbytagname(title)->item(0)->nodevalue; $link = $article->getelementsbytagname(link)->item(0)->nodevalue; $article_array[$id] = array('title'=>$title, 'link'=>$link);}//输出结果echo ;var_dump($article_array);echo
;?>运行结果如下:
更详细的内容请访问php手册中的domdocument类。当然想要更加方便可以使用一些第三方提供的xml类库,这里就不一一列举了,有兴趣可以到网上找找。
http://blog.csdn.net/morewindows/article/details/7241452
其它类似信息

推荐信息