tags:

views:

33

answers:

2

Hi Guys,

I am pretty new to xml parsing and I am using XMLREADER to parse a huge file.

Given the following XML (sample):

<hotels>
 <hotel>
   <name>Bla1</name>
 </hotel>
 <hotel>
  <name>Bla2</name>
 </hotel>
</hotels>

And then the XMLREADER in PHP which pulls up the values to my Database:

$reader = new XMLReader();
$reader->open('hotels.xml');
while ($reader->read()) {

 if ($reader->name == "name") {

   $reader->read();
   mysql_query("INSERT INTO MyHotels (hotelName) VALUES (\"$reader->value\")");
 }

}
$reader->close();

The problem is that I've got a single empty row between each of the parsed nodes!! Not sure why this happens!

 | ID | hotelName |
 | 1  | Bla1      |
 | 2  |           |
 | 3  | Bla2      |
 | 4  |           |

Help is greatly appreciated.

A: 

Make sure that $reader->value is not empty if you want to avoid that:

 if ($reader->name == "name") {
   $reader->read();

   if ($reader->value) {
     mysql_query("INSERT INTO MyHotels (hotelName) VALUES (\"$reader->value\")");
   }
 }
Sarfraz
I suspect he's seeing the `END_ELEMENT` nodes…
Tomalak
A: 

You are seeing the end element (</name>), which is also one step for the reader. So you have to check the node type:

if ($reader->name == "name" && $reader->type == XMLReader::ELEMENT)

to avoid reading in the whitespace node right after the </name>.

Tomalak