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?有沒有更快/更好的方法,而不是在下面的代碼中使用preg_match?
此代碼發現如果在<date_iso></date_iso>
字符串2004年,如果是這樣,我贊同從特定元素的一些數據,搜索字符串被發現。
我想知道這是否是最好的/最快的方法,因爲我主要關心的是速度和XML文件是巨大的。謝謝你的想法。
這是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>
這是代碼
<?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;
}
}
?>
這是另一種方法
<?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;
}
}
?>
我用SAX,XMLReader和SimpleXML做了一些測試。該測試用於回顯2004年在date_iso中找到的所有dc_date。我必須說SAX/XMLReader比simplexml要慢得多...這是我嘗試madwe的源代碼http://codepad.org/7RerAOvB – EnexoOnoma
對於像這樣的簡單情況,XMLReader仍然太高級了 - 訪問者,迭代器等抽象。看看XML解析器 - 只需設置一個入口處理程序,dc_date和date_iso元素來創建一個簡單的狀態機,使用strpos來測試子字符串匹配,並且您很好。像這樣的方法甚至不需要將整個文件讀入內存 - XMLReader的確如此,據我所知並記住。我想當我說'基於SAX'時,我應該將其限定爲'基於事件的SAX解析器'。 – Roel
所以爲了清晰起見,建議我使用XML Parser而不是XMLReader來提高速度和內存性能,對不對? – EnexoOnoma