php - How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader? -
i new in xmlreader, , think kind of hard find tutorials/code or advanced examples. question how can transform code have now, if search (through form) term jquery give me opportunity output value of <info></info>
(and later other elements) in every <name></name>
found in ?
this code output names of books.
<?php $reader = new xmlreader(); $reader->open("books.xml"); while ($reader->read()) { switch ($reader->nodetype) { case (xmlreader::element): if ($reader->localname == "name") { $reader->read(); echo $reader->value; break; }}} ?>
the xml file
<?xml version="1.0" encoding="iso-8859-1"?> <library> <book isbn="781"> <name>scjp 1.5</name> <info>sun certified java programmer book</info> </book> <book isbn="194"> <name>jquery awesome!</name> <info>jquery reference book</info> </book> <book isbn="199"> <name>jquery 101</name> <info>all need know jquery</info> </book> </library>
if you're bound xmlreader sequential parsing can build parser based on it.
one method simplify parsing operation encapsulate iterator, if you're working on sequence. example iterator named xmlbookiterator
foreach
on books while data being parsed:
$books = new xmlbookiterator($file); foreach($books $key => $book) { echo 'book (', $key, '):', "\n"; print_r($book); }
a result example data:
book (0): stdclass object ( [isbn] => 781 [name] => scjp 1.5 [info] => sun certified java programmer book ) book (1): stdclass object ( [isbn] => 194 [name] => jquery awesome! [info] => jquery reference book ) book (2): stdclass object ( [isbn] => 199 [name] => jquery 101 [info] => need know jquery )
then it's left filter books based on term. can implemented filteriterator
, let's call bookfilteriterator
:
$filtered = new bookfilteriterator($books, 'jquery'); foreach($filtered $key => $book) { echo 'book (', $key, '):', "\n"; print_r($book); }
the output reduced matching books:
book (1): stdclass object ( [isbn] => 194 [name] => jquery awesome! [info] => jquery reference book ) book (2): stdclass object ( [isbn] => 199 [name] => jquery 101 [info] => need know jquery )
the thing left actual code this. it's bit longer, in it's heart - next()
function inside iterator find state-based parser reading on xml started in question. difference is, has sort of state helps fill current book entry stored private member of class.
the demo code uses xml string converted pseudo "file" via $file = 'data://text/plain;base64,'.base64_encode($xml);
. iterator works filename, get's passed xmlreader
anyway, large data, use file.
Comments
Post a Comment