Is there any faster/better way instead of using preg_match in the following code? [duplicate]
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.
preg_match
is a regular expression function, if you only need to do simple string comparisons, most often it's recommended to not use regular expression for it.
An alternative to your use of preg_match
would be to compare the beginning of the <date-iso>
contents against the year:
if ($search === substr($entry->date_iso, 0, 4))
as the date is always in the same format (hopefully) and starts with the year. You could also add the -
to the search string and then compare against the first 5 characters.
精彩评论