Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

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 am new in XMLReader, and I think is kind of hard to find tutorials/code or something advanced to get examples. My question is how can I transform the code I have now, so if I search (through a form) the term jQuery will give me the opportunity to output the value of <info></info> (and later other elements) in every <name></name> that is found in ?

This is the code that output the names of the 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 is Awesome!</name>
        <info>jQuery Reference Book</info>
    </book> 
    <book isbn="199">
        <name>jQuery 101</name>
        <info>All you need to know about jQuery</info>
    </book> 
</library>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try simplexml -- it's better:

<?php
$books  = simplexml_load_file('books.xml');
$search = 'jquery';
foreach ($books->book as $book) {
    if (preg_match('/' . preg_quote($search) . '/i', $book->name)) {
        echo $book->name . ' (' . $book->info . ')<br/>';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...