【问题标题】:Searching XML For Data via php通过 php 在 XML 中搜索数据
【发布时间】:2012-03-28 09:57:40
【问题描述】:

我正在尝试使用 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

我希望我的问题很清楚。

【问题讨论】:

  • 请展示一些您尝试过的代码
  • 我目前还没有尝试任何东西,我很困惑该怎么做,因为我从 xml 文件中寻找字符串而不是获取元素的值

标签: php xml search


【解决方案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;
      }
    }
  }
}

【讨论】:

  • 试过这个,应该是引号中的东西还是我得到一个解析错误解析错误:语法错误,第 7 行 /var/www/other_projects/musify/search_output.php 中的意外 T_STRING这是 'if($xml->readString() something something){'
  • 你能告诉我如果 ($xml->readString() something something) the something after readString() 导致错误...
  • 谢谢,在您编辑之前我已经找到了解决方案,但您的回答也有帮助:-)
猜你喜欢
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-24
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多