Home  >  Article  >  Backend Development  >  Reading and writing XML files with PHP_PHP tutorial

Reading and writing XML files with PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:48:291045browse

PHP can easily generate and read XML files. PHP mainly completes XML reading and writing operations through DOMDocument, DOMElement and DOMNodeList. Below is a brief explanation of how to use these classes.

1. Generate XML file
For an XML file as follows.

[html]


PHP Access MySql Database Basics
http://blog.csdn.net/morewindows/article/details/7102362



PHP Access MySql Database Basics
http://blog.csdn.net/morewindows/article/details/7102362

Let’s see how to generate it using PHP:

First create a new DOMDocument object and set the encoding format.

$dom = newDOMDocument('1.0', 'UTF-8');

$dom->formatOutput= true;

Create the

node and the node</p> <p>$rootelement =$dom->createElement("article");</p> <p>$title =$dom->createElement("title", "PHP Access MySql Database - Elementary");</p> <p> </p> <p>Then create a <link> node with text content</p> <p>$link =$dom->createElement("link","http://blog.csdn.net/morewindows/article/details/7102362");</p> <p>You can also generate a <link> node first and then add text content to it. </p> <p>$link = $dom->createElement("link");</p> <p>$linktext =$dom->createTextNode('http://blog.csdn.net/morewindows/article/details/7102362');</p> <p>$link->appendChild($linktext);</p> <p> </p> <p>Then add the <title> and <link> nodes to the <article> node </p> <p>$rootelement->appendChild($title);</p> <p>$rootelement->appendChild($link);</p> <p> </p> <p>Finally, add the <article> node to the DOMDocument object, </p> <p>$dom->appendChild($rootelement);</p> <p> </p> <p>A complete XML is now generated. Then regenerate the entire XML, </p> <p>echo $dom->saveXML() ;</p> <p>saveXML() can also input only part of the XML text. For example, echo $dom->saveXML($link); will only output the <link> node: <link>http://blog.csdn. net/morewindows/article/details/7102362</link></p> <p> </p> <p>The following is a complete example of outputting data content to an XML file in PHP. This example will output a PHP array to an XML file. </p> <p>[php] <?php <br /> //Output the array into an XML file <br /> // by MoreWindows( http://blog.csdn.net/MoreWindows ) <br /> $article_array = array( <br /> "First article" => array( <br> "title"=>"Access MySql Database with PHP - Elementary", <br> "link"=>"http://blog.csdn.net/morewindows/article/details/7102362" <br> ), <br> "Part 2" => array( <br> "title"=>"PHP Access MySql Database Intermediate Smarty Technology", <br> "link"=>"http://blog.csdn.net/morewindows/article/details/7094642" <br> ), <br> "Part 3" => array( <br> "title"=>"PHP Access MySql Database Advanced AJAX Technology", <br> "link"=>"http://blog.csdn.net/morewindows/article/details/7086524" <br> ), <br> ); <br> $dom = new DOMDocument('1.0', 'UTF-8'); <br> $dom->formatOutput = true; <br> $rootelement = $dom->createElement("MoreWindows"); <br> foreach ($article_array as $key=>$value) <br> { <br> $article = $dom->createElement("article", $key); <br> $title = $dom->createElement("title", $value['title']); <br> $link = $dom->createElement("link", $value['link']); <br> $article->appendChild($title); <br> $article->appendChild($link); <br> $rootelement->appendChild($article); <br> } <br> $dom->appendChild($rootelement); <br> $filename = "D:\test.xml"; <br> echo 'XML file size' . $dom->save($filename) . 'Bytes'; <br> ?> <br> <?php<br /> //Output the array to an XML file <br /> // by MoreWindows( http://blog.csdn.net/MoreWindows )<br /> $article_array = array(<br /> "First article" => array(<br /> "title"=>"Access MySql database with PHP - Elementary",<br> "link"=>"http://blog.csdn.net/morewindows/article/details/7102362"<br> ),<br> "Part 2" => array(<br> "title"=>"PHP Access MySql Database Intermediate Smarty Technology",<br> "link"=>"http://blog.csdn.net/morewindows/article/details/7094642"<br> ),<br> "Part 3" => array(<br> "title"=>"PHP Access MySql Database Advanced AJAX Technology",<br> "link"=>"http://blog.csdn.net/morewindows/article/details/7086524"<br> ),<br> );<br> $dom = new DOMDocument('1.0', 'UTF-8');<br> $dom->formatOutput = true;<br> $rootelement = $dom->createElement("MoreWindows");<br> foreach ($article_array as $key=>$value)<br> {<br> $article = $dom->createElement("article", $key);<br> $title = $dom->createElement("title", $value['title']);<br> $link = $dom->createElement("link", $value['link']);<br> $article->appendChild($title);<br> $article->appendChild($link);<br> $rootelement->appendChild($article);<br> }<br> $dom->appendChild($rootelement);<br> $filename = "D:\test.xml";<br> echo 'XML file size' . $dom->save($filename) . 'Bytes';<br> ?><br> Running this PHP will generate the test.xml file on the D drive (Win7 + XAMPP + IE9.0 test passed) </p> <p> </p> <p>2. Read XML file <br> Take reading the D:\test.xml generated in the previous article as an example: </p> <p>[php] <?php <br /> //读取XML文件  <br /> // by MoreWindows( http://blog.csdn.net/MoreWindows )  <br /> $filename = "D:\test.xml"; <br /> $article_array = array(); <br />  <br /> $dom = new DOMDocument('1.0', 'UTF-8'); <br /> $dom->load($filename); <br>  <br> //得到<article>结点  <br> $articles = $dom->getElementsByTagName("article"); <br> echo '<article> 结点个数 ' . $articles->length; <br> foreach ($articles as $article) <br> { <br>     $id = $article->getElementsByTagName("id")->item(0)->nodeValue; <br>     $title = $article->getElementsByTagName("title")->item(0)->nodeValue; <br>     $link = $article->getElementsByTagName("link")->item(0)->nodeValue; <br>     $article_array[$id] = array('title'=>$title, 'link'=>$link); <br> } <br>  <br> //输出结果  <br> echo "<pre class="brush:php;toolbar:false">"; <br> var_dump($article_array); <br> echo "</pre>"; <br> ?> <br> <?php<br /> //读取XML文件<br /> // by MoreWindows( http://blog.csdn.net/MoreWindows )<br /> $filename = "D:\test.xml";<br /> $article_array = array();</p> <p>$dom = new DOMDocument('1.0', 'UTF-8');<br /> $dom->load($filename);</p> <p>//得到<article>结点<br> $articles = $dom->getElementsByTagName("article");<br> echo '<article> 结点个数 ' . $articles->length;<br> foreach ($articles as $article)<br> {<br>  $id = $article->getElementsByTagName("id")->item(0)->nodeValue;<br>  $title = $article->getElementsByTagName("title")->item(0)->nodeValue;<br>  $link = $article->getElementsByTagName("link")->item(0)->nodeValue;<br>  $article_array[$id] = array('title'=>$title, 'link'=>$link);<br> }</p> <p>//输出结果<br> echo "<pre class="brush:php;toolbar:false">";<br> var_dump($article_array);<br> echo "</pre>";<br> ?><br> 运行结果如下:</p> <p> <img alt="" src="http://www.bkjia.com/uploads/allimg/131122/144SK461-0.gif"><br> <br> 摘自 MoreWindows</p> <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/478414.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http://www.bkjia.com/PHPjc/478414.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">PHP可以方便的生成和读取XML文件。PHP主要通过DOMDocument、DOMElement和DOMNodeList来完成XML的读取与写入操作的。下面就简要说明下如何使用这些...</span> </div> <div class="art_confoot"></div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="New features of PHP5.4: Array dereferencing support_PHP tutorial" href="http://m.php.cn/faq/302761.html">New features of PHP5.4: Array dereferencing support_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="New features of PHP5.4: Array dereferencing support_PHP tutorial" href="http://m.php.cn/faq/302763.html">New features of PHP5.4: Array dereferencing support_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="http://m.php.cn/about/us.html">About us</a><a href="http://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="http://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>