我正在尝试使用php在XML文件中搜索数据。我并没有试图获取某些元素的值,如果我想要的话,我会使用xpath。
这是我的XML文件示例:
<root>
<author>foo</author>
<date>bar</date>
</root>
假设我的客户想搜索"fab"这个词。我希望返回所有具有字符"f"、"b"answers"a"的字符串。因此输出为:
Foo
bar
例如,作者的名字可能是James Westside。
<author>James Westside</author>
用户搜索jam
它将返回James Westside
我希望我的问题很清楚。
您应该使用PHP的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;
}
}
}
}