Possible Duplicate:
How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader?
this code finds if there is the string 2004 in <date_iso></date_iso> and if it is so, I echo some data from that specific element that the search string was found.
I was wondering if this is the best/fastest approach because my main concern is speed and the XML file is huge. Thank you for your ideas.
this is a sample of the XML
<entry ID="4406">
<id>4406</id>
<title>Book Look Back at 2002</title>
<link>http://www.sebastian-bergmann.de/blog/archives/33_Book_Look_Back_at_2002.html</link>
<description></description>
<content_encoded></content_encoded>
<dc_date>20.1.2003, 07:11</dc_date>
<date_iso>2003-01-20T07:11</date_iso>
<blog_link/>
<blog_title/>
</entry>
this is the code
<?php
$books = simplexml_load_file('planet.xml');
$search = '2004';
foreach ($books->entry as $entry) {
if (preg_match('/' . preg_quote($search) . '/i', $entry->date_iso)) {
echo $entry->dc_date;
}
}
?>
this is another approach
<?php
$books = simplexml_load_file('planet.xml');
$search = '2004';
$regex = '/' . preg_quote($search) . '/i';
foreach ($books->entry as $entry) {
if (preg_match($regex, $entry->date_iso)) {
echo $entry->dc_date;
}
}
?>
If your main concern is speed, you shouldn’t use simplexml or any other DOM-based xml parsing for this; use a SAX-based parser. Furthermore, don’t use preg_match if you only want to do simple substring matching (use strpos).
If speed isn’t really your concern but being idiomatic is, use an XPath 2.0 implementation (don’t know if there is one for PHP) or do other XPath-based regex matching things – a quick google shows exslt options, or simpler xpath 1.0-based string matching options.