开发者

How to search an XML file's content similar to a MySQL query?

I can read the input of a xml file in an array simply like this :

  <?php
  $doc = new DOMDocument();
  $doc->load( 'books.xml' );

  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;

  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;

  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;

  echo "$title - $author - $publisher\n";
  }
  ?>

And lets the xml file to an example something like this :

  <books>
  <book>
  <aut开发者_JS百科hor>Jack Herrington</author>
  <title>PHP Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  </books>

But If i want to match at a certain level lets say I want to FIND the number of matching elements like in mySql has LIKE or ==.

And return the result to an array or something


XPATH is what you are looking for I think.

For instance, all books published by O'Reilly:

<?php
$doc = new DOMDocument();
$doc->load( '/tmp/books.xml' );
$x = new DOMXPath($doc);
foreach($x->query('//book[publisher="O\'Reilly"]') as $book){
    echo $book->ownerDocument->saveXML($book);
}
//If you only want the count:
echo $x->evaluate('count(//book[publisher="O\'Reilly"])');

XPath is my opinion more easy to learn then SQL, but by no means a 'look at it for a couple of minutes and you're done', you'll really have to learn it if your needs are more complex then the bare basics.


If you parse your document using SimpleXML instead of DOMDocument, you can use xpath to find elements in your document. I don't know if this will match your needs exactly, but I have done some pretty complex, dynamic paths (queries) before:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜