I'm trying to search for data in a XML File using php. I'm not trying to get values of certain elements, I would use xpath if I wanted that.
我正在尝试使用php在XML文件中搜索数据。我不是想要获取某些元素的值,如果我想要的话,我会使用xpath。
This is an example of my XML file:
这是我的XML文件的一个示例:
<root>
<author>foo</author>
<date>bar</date>
</root>
Let's say my client wants to search for the words 'fab'. I want all strings with the character 'f' and 'b' and 'a' to return. So output would be:
假设我的客户想要搜索“fab”这个词。我想要所有带有字符'f'和'b'和'a'的字符串返回。所以输出将是:
Foo
bar
The author name could be James Westside for example.
例如,作者姓名可以是James Westside。
<author>James Westside</author>
And the user searched for jam
it would return James Westside
并且用户搜索了它将返回James Westside
I hope my question is clear.
我希望我的问题很清楚。
1 个解决方案
#1
1
You should use PHP:s XMLReader class. XMLReader acts as a cursor going forward on the document stream and stopping at each node on the way.
您应该使用PHP:XMLReader类。 XMLReader充当游标在文档流上前进,并在途中停止在每个节点上。
Something like this:
像这样的东西:
$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;
}
}
}
}
#1
1
You should use PHP:s XMLReader class. XMLReader acts as a cursor going forward on the document stream and stopping at each node on the way.
您应该使用PHP:XMLReader类。 XMLReader充当游标在文档流上前进,并在途中停止在每个节点上。
Something like this:
像这样的东西:
$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;
}
}
}
}