繁体   English   中英

通过php搜索XML以获取数据

[英]Searching XML For Data via php

我正在尝试使用php搜索XML文件中的数据。 我不是要获取某些元素的值,如果需要的话,我会使用xpath。

这是我的XML文件的示例:

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

假设我的客户想要搜索“ fab”一词。 我希望所有带有字符“ f”,“ b”和“ a”的字符串返回。 因此输出将是:

Foo
bar

例如,作者姓名可能是James Westside。

<author>James Westside</author>

并且用户搜索了jam ,它将返回James Westside

希望我的问题清楚。

您应该使用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;
      }
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM