【问题标题】:xpath searching with php使用 php 进行 xpath 搜索
【发布时间】:2012-03-21 10:06:44
【问题描述】:

我正在尝试使用 XPATH 使用表单中的值搜索 XML 文档,但遇到了一些错误。

警告:SimpleXMLElement::xpath() [simplexmlelement.xpath]:无效 第 17 行的表达式

警告:SimpleXMLElement::xpath() [simplexmlelement.xpath]:xmlXPathEval:第 17 行评估失败

警告:在第 21 行为 foreach() 提供的参数无效

holidays.xml sn-p

<channel>
    <item>
          <title>Holiday description</title> 
          <link>link</link> 
          <description>Holiday description</description> 
          <pubDate>Sun, 13 Feb 2011 11:58:17 GMT</pubDate> 
          <guid>http://site</guid> 
      </item>
</channel

txtSearch 是从表单中获取的文本值。任何人都可以解释解决这些错误吗?

【问题讨论】:

    标签: php xml search xpath


    【解决方案1】:

    改变这一行

    $qry = "channel/item/[contains(text()),'$txtSearch']";
    

    到这里

    $qry = sprintf('channel/item[contains(., "%s")]', $txtSearch);
    

    然后它应该可以工作了。

    请注意,当您使用'channel' 时,查询是相对于您调用xpath 方法的SimpleXMLElement。如果要从根节点开始,请使用 '/channel'。当您想在文档中的任何地方搜索时,请使用'//channel'。

    也看看这个XPath tutorial。

    【讨论】:

      【解决方案2】:

      你在这行有错误$qry = "channel/item/[contains(text()),'$txtSearch']"; 错误的括号关闭。您还应该指定要搜索的节点,对于description 节点,您可以使用以下xpath: $qry = "//channel/item[description[contains(text(),\"$txtSearch\")]]";

      更新: 当然,戈登的变种更好:$qry = "//channel/item[contains(.,\"$txtSearch\")]";

      【讨论】:

        猜你喜欢
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 2019-11-16
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多