Reputation: 3362
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>
<author>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
Upvotes: 0
Views: 1401
Reputation: 70510
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.
Upvotes: 2
Reputation: 15390
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
Upvotes: 0