HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

In need to speed up this code that filters the data of XML using XMLReader

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thistheneedxmlthatfiltersusingcodexmlreaderdata

Problem

I am using XMLReader and avoided SimpleXML because I must handle a huge file and for memory issues, SimpleXML is not the ideal solution. However, even I coded the below script in SimpleXML, it gives me the result really much faster.

Because speed and memory is a must for this project, is there any way to speed up this code? What it does, it filters the books and show those that contains the word jQuery.

```
error_reporting(~0);

$xml =


SCJP 1.5
Sun Certified Java Programmer book


jQuery is Awesome!
jQuery Reference Book


jQuery 101
All you need to know about jQuery


EOD;

$file = 'data://text/plain;base64,'.base64_encode($xml);

class XMLBookIterator implements iterator
{
private $file;
private $reader;
private $state;
private $key = 0;
private $book;
private $valid;
public function __construct($file)
{
$this->file = $file;
}
public function current()
{
return $this->book;
}
public function key()
{
return $this->key;
}
public function next()
{
$reader = $this->reader;
while ($next = $reader->read())
{
switch ($reader->nodeType)
{
case (XMLREADER::ELEMENT):
$case = $reader->localName.'|'.$this->state;
switch($case)
{
case 'library|0':
break;
case 'book|1':
$this->book = new stdClass;
$this->book->isbn = $reader->getAttribute('isbn');
break;
case 'name|2':
$this->book->name = $reader->readInnerXML();
break;
case 'info|3':
$this->book->info = $reader->readInnerXML();

Solution

Your code seems quite tidy and easy to understand, congratulations. But maybe you can check for built in functionality. XPath can search items for you:

http://www.php.net/manual/en/simplexmlelement.xpath.php

http://www.w3schools.com/xpath/xpath_syntax.asp

Context

StackExchange Code Review Q#3585, answer score: 2

Revisions (0)

No revisions yet.