宋濂嗜学小古文:PHP 5 XMLReader: Reading XML with Namespace (...

来源:百度文库 编辑:偶看新闻 时间:2024/05/09 03:54:19
PHP 5 XMLReader: Reading XML with Namespace (Part 2)
By alif - Posted on 08 April 2009
Tweet
This is a continuation of previous article, where I wrote on how to use PHP'5 DOM to read XML Files easily. But, for large files, its better to useXMLReader. Unlike DomDocument, XMLReader does not load the entire File on memory. It reads an XML file one node at a time. I hardly use XMLReader because it requires writing a lot of codes, but for extremely large XML Files, its better to use it. Full reference on XMLReader can beviewed here. It requires PHP 5.2.
The following are the functions I use:
open - opens XML File
read - reads node of XML
getAttribute - gets the attribute of a node
moveToNextAttribute - moves to next Attribute
next - moves to next node
Here's a Basic XML File called 'test.xml':
01.
02.
03.
04.SCJP 1.5
05.
06.

07.
08.jQuery is Awesome!
09.
10.

11.

Below is a way to read it:
At first initialize and open the XML file
1.$xmlReader = new XMLReader();
2.// open the file for reading
3.$xmlReader->open('test.xml')
Now keep reading nodes until the end has been reached, which done by a while loop:
1.while($xmlReader->read()) {
2.
3.}
Below is the full code:
01.$bookList = array();
02.$i=0;
03.$xmlReader = new XMLReader();
04.$xmlReader->open('test.xml');
05.while($xmlReader->read()) {
06.// check to ensure nodeType is an Element not attribute or #Text
07.if($xmlReader->nodeType == XMLReader::ELEMENT) {
08.if($xmlReader->localName == 'book') {
09.$bookList[$i]['book_isbn'] = $xmlReader->getAttribute('isbn');
10.}
11.if($xmlReader->localName == 'name') {
12.// move to its textnode / child
13.$xmlReader->read();
14.$bookList[$i]['name'] = $xmlReader->value;
15.}
16.if($xmlReader->localName == 'info') {
17.// move to its textnode / child
18.$xmlReader->read();
19.$bookList[$i]['info'] = $xmlReader->value;
20.$i++;
21.}
22.
23.}
24.}
Here's a var_dump of $bookList
01.array(2) {
02.[3]=>
03.array(3) {
04.["book_isbn"]=>
05.string(3) "781"
06.["name"]=>
07.string(8) "SCJP 1.5"
08.["info"]=>
09.string(34) "Sun Certified Java Programmer book"
10.}
11.[4]=>
12.array(3) {
13.["book_isbn"]=>
14.string(3) "194"
15.["name"]=>
16.string(18) "jQuery is Awesome!"
17.["info"]=>
18.string(21) "jQuery Reference Book"
19.}
20.}
That's about it. It requires writing a lot of codes, but it's useful for large (by large I mean extremely large) XML files.
However, when the XML files is very complex (and not extremely large), I find both DomDocument or XMLReader are not ideal solution. I rather use XPath (DomXPath), which I will hopefully write in my next article.
AttachmentSize
test.xml300 bytes
xmlreader_test.php.txt677 bytes
alif's blog
TagsPHP
XML