2012-03-28 115 views
0

我正在嘗試使用php搜索XML文件中的數據。 我不想獲取某些元素的值,如果我想要,我會使用xpath。通過php搜索XML數據

這是我的XML文件的例子:

<root> 
<author>foo</author> 
<date>bar</date> 
</root> 

比方說,我的客戶希望搜索詞「工廠」。 我想要所有帶字符'f'和'b'和'a'的字符串返回。 所以輸出將是:

Foo 
bar 

作者姓名可能是詹姆斯·西城爲例。

<author>James Westside</author> 

而且用戶搜索jam 它將返回James Westside

我希望我的問題是清楚的。

+0

請出示一些代碼,你已經嘗試 – 2012-03-28 10:02:31

+0

我還沒有在此刻嘗試新鮮事物,即時通訊在做什麼,因爲即時尋找從XML文件中的字符串很困惑,而比抓取元素的值 – 2012-03-28 10:07:55

回答

1

您應該使用PHP:s XMLReader類。 XMLReader充當向文檔流前進的光標,並在路上的每個節點處停止。

事情是這樣的:

$search_phrase = 'fab'; 

$xml = new XMLReader; 
$xml->open('your-xml-file.xml'); 

while ($xml->read()) { 
    $node = $xml->expand(); 

    /* Looping through all elements in the XML */ 

    /* Test if the current node is a text node: */ 
    if ($node->nodeType == XMLReader::TEXT) { 

    /* Loop all letters in search_phrase */ 
    for ($i = 0; $i < strlen($search_phrase); $i++) { 

     /* Test if the text in the text node is matching any letter i search_phrase: */ 
     if (strpos($node->nodeValue, substr($search_phrase, $i, 1)) !== false) { 
     echo($node->nodeValue . "\n"); 
     break; 
     } 
    } 
    } 
} 
+0

試過這個,應該是某些東西應該在引號或什麼的東西 我得到一個解析錯誤 解析錯誤:語法錯誤,意想不到的T_STRING在/var/www/other_projects/musify/search_output.php在線7是'如果($ xml-> readString()的東西){' – 2012-03-28 12:22:23

+0

你能告訴我如果($ xml-> readString()東西) readString()導致錯誤之後的東西... – 2012-03-28 12:39:14

+0

Hello Marshall!我使我的示例代碼更加詳細。 – 2012-03-28 14:08:40